java xml document.getTextContent() stays empty - java

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?

Related

java XML to string issue

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

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);

Update XML attribute value in document tree

I am not too sure why i cannot modify an attribute to my xml. The code below i used to get the read the attributes from the XML. Pulls the attributes without any issues.
document = documentBuilder.parse(file);
NodeList sessionNodelist = document.getElementsByTagName("session");
if (sessionNodelist.getLength() > 0)
{
Element sessionElement = (Element) sessionNodelist.item(0);
String timeout = sessionElement.getAttribute("timeout");
String warning = sessionElement.getAttribute("warning");
}
Now when i go to set them, it doesn't work and I am not too sure why. The code is below. it's the exact same code i used to pull the atribles, but instead of the getAttribute i used setAttribute which takes two parameters. setAttribute(String name, String Value).
document = documentBuilder.parse(file);
NodeList sessionNodelist = document.getElementsByTagName("session");
if (sessionNodelist.getLength() > 0)
{
Element sessionElement = (Element) sessionNodelist.item(0);
sessionElement.setAttribute("timeout","12");
sessionElement.setAttribute("warning", "10");
}
Any ideas?
You need to write the document tree back to the XML file. See this page for how to write a DOM tree to a file.
You would use a javax.xml.transform.Transformer to write the object into the file as follows:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);

How to convert xml Element and its child nodes into String in Java?

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 Document to String

What's the simplest way to get the String representation of a XML Document (org.w3c.dom.Document)? That is all nodes will be on a single line.
As an example, from
<root>
<a>trge</a>
<b>156</b>
</root>
(this is only a tree representation, in my code it's a org.w3c.dom.Document object, so I can't treat it as a String)
to
"<root> <a>trge</a> <b>156</b> </root>"
Thanks!
Assuming doc is your instance of org.w3c.dom.Document:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
Use the Apache XMLSerializer
here's an example:
http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
http://www.netomatix.com/XmlFileToString.aspx
First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

Categories