Here is the code:
Response resp = tkMarC.getClock(TK_Base.Format.xml);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String xml = resp.getBody();
System.out.println(xml);
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++)
{
System.out.println(nl.item(i).toString());
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
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>
<status>
<current>open</current>
<next>after</next>
<change_at>16:00:00</change_at>
</status>
<message>Market is open</message>
<unixtime>1437676225</unixtime>
</response>
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.