Hasitha Jayawardana
Hasitha Jayawardana

Reputation: 2436

How to Read XML Response using Java

I am calling a web service and get the response as XML. Here is XML response,

<Response>
    <NO>1</NO>
    <NAME>John Doe</NAME>
</Response>
<Response>
    <NO>2</NO>
    <NAME>Jane Doe</NAME>
</Response>

I am trying to get each data from each response. I need to get each value.

Here is my Java code,

Document document = DocumentBuilderFactory
                    .newInstance()
                    .newDocumentBuilder()
                    .parse(new InputSource(new StringReader(response.toString())));

            NodeList nodeList = document.getElementsByTagName("Response");
            System.out.println(nodeList.getLength());

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

                    NodeList id = (NodeList) element.getElementsByTagName("Response");
                    System.out.println(id);
                    NodeList nodeLists = element.getChildNodes();

                    for (int j = 0; j < nodeLists.getLength(); j++) {
                        Node n = nodeLists.item(j);

                        if (n.getNodeType() == Node.ELEMENT_NODE) {
                            Element name = (Element) n;
                            System.out.println(name.getAttributes().getNamedItem("NO").getNodeValue());
                            System.out.println(name.getAttributes().getNamedItem("NAME").getNodeValue());
                        }
                    }
                }
            }

But I can't get What I need. Nothing prints.

I need to print each value like this,

1
John Doe
2
Jane Doe

Basically, it needs to iterate over all <Response> Tags and give me the available data. But my code doesn't work.

So anybody can help me? Greatly appreciate that.

Upvotes: 2

Views: 13978

Answers (2)

Akash Shah
Akash Shah

Reputation: 616

I never work on XML parsing but when I debug your Code in my machine I got an error something like,

[Fatal Error] :1:84: The markup in the document following the root element must be well-formed.
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 84; The markup in the document following the root element must be well-formed.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at com.flotomate.fd.system.etc.OprUtility.main(OprUtility.java:87)

and search on StackOverflow what cause I got an error I find this Answer

issue is not root element Added.

after I add root element still not fix. so I follow pattern same as Answer

not Sure optimize and well define but working

String response = " <root>"
                      +"   <Response>  "
                      + "       <NO>1</NO>  "
                      + "       <NAME>John Doe</NAME>  " 
                      + "   </Response>  " 
                      + "   <Response>  "
                      + "       <NO>2</NO>  " 
                      + "       <NAME>Jane Doe</NAME>  " 
                      + "  </Response>  "
                      + "</root>";
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
            new InputSource(new StringReader(response.toString())));

    NodeList nodeList = document.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element.getNodeName().contains("Response")) {
            System.out.println(element.getElementsByTagName("NO").item(0).getTextContent());
            System.out.println(element.getElementsByTagName("NAME").item(0).getTextContent());
        }
    }
}

    //And from this also.....
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element element1 = (Element) nodeList.item(i);
                System.out.println(element.getElementsByTagName("NO").item(0).getTextContent());
                System.out.println(element.getElementsByTagName("NAME").item(0).getTextContent());
    }

output:

1
John Doe
2
Jane Doe

Upvotes: 6

HariUserX
HariUserX

Reputation: 1334

NodeList id = (NodeList) element.getElementsByTagName("Response");

This will give you a nodelist of all elements with tagname Response. But you are not using this node list in your below code. Rather you are iterating on element.getChildNodes(). You should iterate on the id, or more specifically id is your required nodelist.

Upvotes: 2

Related Questions