0

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.

1
  • 1
    Probably becuase you are just reading <?xml-stylesheet> attributes. You should follow some tutorial on how to read a complete XML first. Does could be tricky at first. Here is a good start Java XML Commented Oct 9, 2017 at 13:31

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but is there a way where I can get the name="" of each child node? Or else it will be difficult to determine when I have found the correct value.
Sure, there is, cast the Node to Element (docs.oracle.com/javase/7/docs/api/org/w3c/dom/Element.html) node and use getAttribute("name")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.