Java xml document.getTextContent () stays empty

I am trying to create 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); 

However, the document remains empty (i.e. println gives null .) I do not know why this is so. The actual problem is that the subsequent XPath expression throws an error: Unable to evaluate expression using this context .

+4
source share
2 answers

The return value of getTextContent on Document defined as null. See Node .

To return to the textual content, call getTextNode on the root element

+2
source

I assume that you want to serialize the document in order to pass it to a test file. To do this, you need to transfer your document to an empty XSL transformer, for example:

 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 print XML well with Java?

0
source

All Articles