Tikky Tikky - 4 months ago 4x
Java Question

Cannot convert String to DOM in Java

Here is the code:

Response resp = tkMarC.getClock(TK_Base.Format.xml);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String xml = resp.getBody();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document docu = db.parse(is);
if (docu != null)
NodeList nl = docu.getChildNodes();
for(int i=0; i<nl.getLength(); i++)
} catch (Exception ex) {

And here is the output from System.out.println(xml)

<?xml version="1.0" encoding="UTF-8"?>
<response id="-5b6df009:14ebc2afaf9:-3779">
<date>2015-07-23 14:30:25.134000</date>
<message>Market is open</message>

However the
sr object always shows:
The length of the characterstream is 307 but str is null
docu object always shows:
docu = (com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl) [#document: null]

and hence no ChildNodes are retrievable as this is what gets output:
[response: null] on console when code enters the for loop on i=0

What am I missing here? I also tried to convert the message to a byte stream via ByteArrayInputStream(xml.getBytes()); and pass that in as an input source but got the same result there is something I guess I don't quite grasp and was unable to find searching the forums.


This is perfectly normal. Your code works fine. You're only confused by the toString() of your element. The toString() of an element will show the tag name followed by the node value. For elements, the node value is null, hence you get [response: null].

Seen in NodeImpl.class:

/** NON-DOM method for debugging convenience. */
public String toString() {
    return "["+getNodeName()+": "+getNodeValue()+"]";

So you're getting your top element, response, properly.