XStream apostrophe Issue in converting Java Object to XML - java

I am using com.thoughtworks.xstream.XStream to Generate xml String. I parse Object to xstream.toXML method and I get the xml output according to the way I need.
<myxml>
<test type="test" name="test">
<question id="Name" answer="Micheal"/>
<question id="Address" answer="Home">
<details name="First Address">
<detailanswer>friend&apos;s House</detailanswer>
</details>
</basequestion>
</test>
</myxml>
XStream xstream = new XStream();
xstream.alias("myxml", MyXml.class);
xstream.alias("test", Test.class);
xstream.alias("question", Question.class);
xstream.alias("details", Details.class);
xstream.alias("detailanswer", String.class);
xstream.addImplicitCollection(MyXml.class, "test");
xstream.addImplicitCollection(Test.class, "question");
xstream.addImplicitCollection(Question.class, "details");
xstream.addImplicitCollection(Details.class, "detailanswer");
xstream.useAttributeFor(Test.class, "type");
xstream.useAttributeFor(Test.class, "name");
xstream.useAttributeFor(Question.class, "id");
xstream.useAttributeFor(Question.class, "answer");
xstream.useAttributeFor(Details.class, "name");
return xstream.toXML(eform);
Following is the Object structure.
Inside MyXml there is List<Test>
Test has List<Question>, String type, String name
Question has List<Details>, String id, String answer.
Details has List<String> detailAnswer, String name
So the element in the question, Friend's house is added to the List detailAnswer in Details class.
I get friend&apos;s House instead of friend's house. How can I resolve this. Is there special way to convert using XStream?

I think its better to use java method to replace a character.
xStream.toXML(testPojo).replaceAll("&apos;", "'")

Related

Gson.toJson() method returns string embedded with "data"

I am working on Workfusion which is one of the automation tool and it consists of selenium, java and Web -harvest technology.
Below is the snipped of my code.
<while condition="${continue_flg}" maxloops="${full_data.size()-1}"
index="ind">
<script><![CDATA[
import com.google.gson.Gson;
Gson gson = new Gson();
LinkedHashMap recMapTemp1 = full_data[ind.toInt()];
println "*****"+recMapTemp1; // Contains key value map
jsonValueMap = gson.toJson(recMapTemp1);
println "*****"+jsonValueMap; // "data" is added before value
]]></script>
<insert-datastore datastore-name="Fallout_type"
json-value-map="${jsonValueMap}" create="true" />
</while>
In map Key is "ship to ctry cd" and Value is "AT" but after converting toJson String it gives as below.
I dont need this data word i need normal Json Value.
"ship to ctry cd":{"data":"AT"},
you can do :
println "*****"+jsonValueMap.data;
to achieve that

searching string and appending

I have below xml in string object
<Emp>
<e1>
<x>ABC</x>
</e1>
<e2>
<x>XYZ</x>
</e2>
<e3>
<x>TTT</x>
</e3>
</Emp>
if i search string with "ABC" then i want to add test
so xml became
<Emp>
<e1>
<x>ABC</x>
<fail>test</fail>
</e1>
<e2>
<x>XYZ</x>
</e2>
<e3>
<x>TTT</x>
</e3>
</Emp>
if i search string with "XYZ" then i want to add test in e2
<Emp>
<e1>
<x>ABC</x>
</e1>
<e2>
<x>XYZ</x>
<fail>test</fail>
</e2>
<e3>
<x>TTT</x>
</e3>
</Emp>
Please let me know whow to use sub string here.

Changing XML values in Android/Java

I want to take an XML file as input which contains the following:
<?xml version='1.0' encoding='utf-8' standalone='yes'>
<map>
<int name="count" value="10" />
</map>
and, read and change the value from 10 to any other integer value.
How can I do this in Android/Java. I'm new to Android and Java and all the tutorials available on the internet are way too complicated.
Thank You
You can change the value by matching the pattern and replacing the string as like below,
String xmlString = "<int name=\"count\" value=\"10\" />";
int newValue = 100;
Pattern pattern = Pattern.compile("(<int name=\"count\" value=\")([0-9]{0,})(\" />)");
Matcher matcher = pattern.matcher(xmlString);
while (matcher.find()) {
String match = matcher.group(2);
xmlString = xmlString.replace(match, String.valueOf(newValue));
}
System.out.println(xmlString);
You can find your answer here. It is like parsing json. You can cast your string(from file) to object and do anything with parameters

JSONException: no value for XYZ when trying to getString("XYZ")

I am doing JSON parsing in Android by the following steps:
Get an XML response from a web-service using HttpPost object.
Convert this XML to JSON string then JSON object.
Now the problem is that sometimes the XML response has null string or Null tag.
For Example:
<data>
<name>Martin Clark</name>
<city>London</city>
<country>XYZ</country> or <country /> <!-- Sometimes it will blank string like this if country is not available -->
<age>27</age>
</data>
Parsing style:
jsonObject.getString("country"); // It is working perfect when xml is this : <country>XYZ<country/>
jsonObject.getString("country"); // It is giving Exception key is not found when xml is this : <country />
i don't understand why the parser is not giving me BLANK string for blank XML object.
By deep level debugging i have found that XML to JSON converter not produce object corresponding to blank xml object.
Please help me.
Use optString instead, catching the Exception is costly and unnecessary.
public String optString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns the empty string if no such mapping
exists.
public String optString (String name, String fallback)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns fallback if no such mapping exists.
Documentation
You can use ths logical solution for your problem.
Try this once.
public static String getStringFromJSON(JSONObject json, String key){
String value = ""; // Blank string by default.
try {
String value = json.getString(key);
return value;
}
catch(JSONException exp){
exp.getMessage();
}
return value; // this wil return BLANk string if object is not prasent.
}
You can you this method for getting String from json object,

JAXB Unmarshalling an subset of Unknown XML content

I have a requirement to unmarshall a subset of Unknown XML content, with that unmarshalled object, I need modify some contents and re-bind the same XML content(subset) with the Original XML.
Sample Input XML:
<Message>
<x>
</x>
<y>
</y>
<z>
</z>
<!-- Need to unmarshall this content to "Content" - java Object -->
<Content>
<Name>Robin</Name>
<Role>SM</Role>
<Status>Active</Status>
</Content>
.....
</Message>
Need to unmarshall the <Content> tag alone, by keeping the other XML part as same. Need to modify the elements in <Content> tag and bind the modified XML part with the original as shown below:
Expected Output XML:
<Message>
<x>
</x>
<y>
</y>
<z>
</z>
<!-- Need to unmarshall this content to "Content" - java Object -->
<Content>
<Name>Robin_123</Name>
<Role>Senior Member</Role>
<Status>1</Status>
</Content>
.....
</Message>
My Questions:
What is the possible solution for this Requirement ? (Except DOM parsing - as XML contnet is very huge)
Is there any option to do this in JAXB2.0 ?
Please provide your suggestions on this.
Consider cutting your source document down to size using the StAX API.
For the given sample, this code creates a DOM document with a root element of the Content element:
class ContentFinder implements StreamFilter {
private boolean capture = false;
#Override public boolean accept(XMLStreamReader xml) {
if (xml.isStartElement() && "Content".equals(xml.getLocalName())) {
capture = true;
} else if (xml.isEndElement() && "Content".equals(xml.getLocalName())) {
capture = false;
return true;
}
return capture;
}
}
XMLInputFactory inFactory = XMLInputFactory.newFactory();
XMLStreamReader reader = inFactory.createXMLStreamReader(inputStream);
reader = inFactory.createFilteredReader(reader, new ContentFinder());
Source src = new StAXSource(reader);
DOMResult res = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(src, res);
Document doc = (Document) res.getNode();
This can then be passed to JAXB as a DOMSource.
Similar techniques can be used when rewriting the XML on output.
JAXB doesn't seem to accept a StreamSource directly, at least in the Oracle 1.7 implementation.
You can annotate an Object property on your class with #XmlAnyElement and by default the unmapped content will be captured as a DOM nodes. If you specify a DomHandler on the #XmlAnyElement then you can control the format. Here is a link to an example where the content is kept as a String.
JAXB use String as it is

Categories