5

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
xtofl
  • 40,723
  • 12
  • 105
  • 192

2 Answers2

2

The return value of getTextContent on Document is defined to null- See Node.

To retreive the text contents call getTextNode on the root element

jontro
  • 10,241
  • 6
  • 46
  • 71
0

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?

Community
  • 1
  • 1
prote
  • 1
  • 1
  • Though this is a nice-to-have, I was rather concerned that my document was empty. Thanks anyway. – xtofl Jan 11 '13 at 14:41