Khaine775
Khaine775

Reputation: 2765

XML Document is null after parsing string containing XML

I have an XML document that looks like this:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/resources/transform.xslt"?>
<map name="response">
    <prop name="numConsumers">87</prop>
    <prop name="numOutEventsQueued">17</prop>
    <prop name="numOutEventsUnAcked">2131</prop>
    <prop name="numOutEventsSent">538108577</prop>
</map>

I get the response as a string, so I parse it to XML and try to extract numConsumers (the value 87):

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;

        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));

        NodeList nodeList  = doc.getChildNodes();
        for(int i = 0; i < nodeList.getLength(); i++) {
            String numConsumers = nodeList.item(i).getTextContent();
        }

But the thing is, when i = 0, numConsumers is type="text/xsl" href="/resources/transform.xslt" and when i = 1, it is all the values of the child nodes, concatenated. What am I doing wrong? I'm aware that the current code is not explicitly looking for the node I want, but at this point I'm just trying to see if I can get to any of the nodes.

Upvotes: 0

Views: 556

Answers (1)

Ironluca
Ironluca

Reputation: 3762

NodeList nodeList  = doc.getChildNodes();

In XML DOM everything is a node. The document in your case has 2 nodes at document level the declaration node ('xml-stylesheet') and the document element ('map'). Depending on the configuration of the parser, if there are any white spaces (and schema , which you dont have, allows it) before or after document element, you would have got that.

One of the way to get what you are at is the below:

NodeList nodeList=doc.getDocumentElement().getElementsByTagName("prop");
for(int i=0;i<nodeList.getLength();i++{

 String number=nodeList.item(i).getFirstChild().getNodeValue();

}

Notice the .getFirstChild().getNodeValue(), in XML DOM everything is a node, internal content of an element node is not the value of the node, it is the first child of the node, the value of the first child is '87' or some other value.

Upvotes: 1

Related Questions