java XML to string issue - java

I tried to solve my xml issue but I am stuck... I am getting the xml as System.Out at console quite well. However when I tried to get it as a return string value, it gives me only half of the xml (the returned string does not contain error but it's broken xml). The code is below. (ide: androidstudio, tried jdk 1.7/1.8 same result)
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
// Output to console for testing
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult); // this give all data to as System.Out as correct every line
xmlString = result.getWriter().toString();
Log.v("XML OUTPUT xmlString", xmlString.toString()); // but this gives only part of xml like broken from half part...
Update:
Solution, there is nothing wrong but Log.v cuts string... this means code is working. thanks for tip to #wero

Related

Pre-added Whitespaces in XML on first line only

I am facing an issue while generating XML through Java code. I am printing the xml directly onto webpage to present the stats. The first line of the generated XML is always having some spaces at the start which makes the XML look weird. How do I remove the same. I tried removing the xml line but still whatever be the first line it has pre white spaces.
Please let me now how do i remove it
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<headNode>
<statsHead1>
<totalCount>0.05</totalCount>
</statsHead1>
<statsHead2>
<statsSubHead1>
<count1>0</count1>
<count2>0.0</count2>
</statsSubHead1>
<statsSubHead2>
<count1>0</count1>
<count2>0.0</count2>
</statsSubHead2>
<totalcount1>0</totalcount1>
<totalcount2>0.0</totalcount2>
</statsHead2>
</headNode>
Code that I use is
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StringWriter outWriter = new StringWriter();
Result result = new StreamResult(outWriter);
transformer.transform(source, result);
return outWriter.toString();

DOM XML Public Doctype not appearing in result xml file

I have written a code to generate XML files. I am stuck at defining doctype for the XML as it should be public. I am able to get SYSTEM doctype successfully but somehow not able to get public doctype written in XML. Below code for SYSTEM doctype is working but same snippet for PUBLIC doctype is not working :
String xmldestpath = "C:/failed/tester.xml";
doctype2 = CreateDoctypeString();
StreamResult result = new StreamResult(new File(xmldestpath ));
try {
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"TEST");
transformer.transform(source, result);
// logger.debug("COMPLETED Copying xml files /....!!");
System.out.println("COMPLETED Copying xml files to bulk import....!!");
Not working snippet. Its not giving error but no doctype is appearing in resultant xml:
String xmldestpath = "C:/failed/tester.xml";
doctype2 = CreateDoctypeString();
StreamResult result = new StreamResult(new File(xmldestpath ));
try {
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"TEST");
transformer.transform(source, result);
// //logger.debug("COMPLETED Copying xml files /....!!");
System.out.println("COMPLETED Copying xml files to bulk import....!!");
If you know you need/want PUBLIC, perhaps you should know that a public literal cannot exist without a system literal.
The XML specification shows:
ExternalID ::= 'SYSTEM' S SystemLiteral
| 'PUBLIC' S PubidLiteral S SystemLiteral
So it should be easy to conclude that you need to specify both in order to get it to work, as demonstrated by this MCVE:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "TEST1");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "TEST2");
transformer.transform(new StreamSource(new StringReader("<Root></Root>")),
new StreamResult(System.out));
Output
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Root PUBLIC "TEST1" "TEST2">
<Root/>

Get XML corresponding to node [duplicate]

Hi I want to convert XML node and its child into a string with its node names.
For example I get a node from XML document which is look like this:
<Name>
<Work>*86</Work>
<Home>*86</Home>
<Mobile>*80</Mobile>
<Work>0</Work>
</Name>
I want to convert whole node into string. With nodenames, not only text. Any help in this regards is greatly appreciated. Thanks.
you can use JDom XMLOutputter subject to the condition that your Element is an org.jdom.Element:
XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(your_jdom_element);
You can use a transformer for that:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

XML Node to String Conversion for Large Sized XML

Till now I was using DOMSource to transform the XML file into string, in my Android App.
Here's my code :
public String convertElementToString (Node element) throws TransformerConfigurationException, TransformerFactoryConfigurationError
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(element);
try {
transformer.transform(source, result);
}
catch (TransformerException e) {
Log.e("CONVERT_ELEMENT_TO_STRING", "converting element to string failed. Aborting", e);
}
String xmlString = result.getWriter().toString();
xmlString = xmlString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
xmlString = xmlString.replace("\n", "");
return xmlString;
}
This was working fine for small xml files.
But for large sized xml this code started throwing OutOfMemoryError.
What may be the reason behind it and how to rectify this problem?
First off: if you just need the XML as a string, and aren't using the Node for anything else, you should use StAX (Streaming API for XML) instead, as that has a much lower memory footprint. You'll find StAX in the javax.xml.stream package of the standard libraries.
One improvement to your current code would be to change the line
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
to
transformer.setOutputProperty(OutputKeys.INDENT, "no");
Since you're stripping newlines anyway at the end of the method, it's not very useful to request additional indentation in the output. It's a small thing, but might reduce your memory requirements a bit if there are a lot of tags (hence, newlines and whitespace for indentation) in your XML.

java xml document.getTextContent() stays empty

I'm trying to build an xml document in a JUnit test.
doc=docBuilder.newDocument();
Element root = doc.createElement("Settings");
doc.appendChild(root);
Element label0 = doc.createElement("label_0");
root.appendChild(label0);
String s=doc.getTextContent();
System.out.println(s);
Yet the document stays empty (i.e. the println yields null.) I don'thave a clue why that is. The actual problem is that a subsequent XPath expression throws the error: Unable to evaluate expression using this context.
The return value of getTextContent on Document is defined to null- See Node.
To retreive the text contents call getTextNode on the root element
I imagine you want to serialize the document to pass it to the test case.
To do this you have to pass your document to an empty XSL transformer, like this:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
See also: How to pretty print XML from Java?

Categories