0

I have the XML as below

<Result>
   <error><SubTask name="witbe" status="ERROR running Witbe" /></error>
   <error><subtask name="VerifyDataServices" status="FAILURE" /></error>
   .... multiple error tags

</Result>

I want to retrieve the entire stuff under the error tag no matter what tag is there inside it. I was trying to parse that with XPath but getting null as the value of error

The code I'm using

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        if (null != inputStream)
        {
            Document doc = db.parse(inputStream);

            XPath xPath =  XPathFactory.newInstance().newXPath();

            String errorTag = "/Result/error";

            NodeList nodeList = (NodeList) xPath.compile(errorTag).evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < nodeList.getLength(); i++) {
                System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
            }


        }

Any idea how to fix this?

3 Answers 3

1
if (nodeList.getLength() > 0) {
    for (int i = 0; i < nodeList.getLength(); i++) {
          Node node = nodeList.item(i);
          if (node.hasChildNodes()) {
              Node childNode = node.getFirstChild();
              System.out.println(childNode.getAttributes().getNamedItem("name") 
                          + " : " + childNode.getAttributes().getNamedItem("status"));
          }
    }
}

Above code will print following output:

name="witbe" : status="ERROR running Witbe"
name="VerifyDataServices" : status="FAILURE"

Do you need these values?

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

Comments

0

Imagine you just putted the all file in a new string called "xml".

String[] xmllines = xml.split('\n');

for(int i = 0; i< xmllines.length(); i++){

    if(xmllines[i].startsWith("<error>"){
         xmllines[i] = xmllines[i].replace("<error>", "");
         xmllines[i] = xmllines[i].replace("</error>", "");
    }
    else {
         xmllines[i] = "";
    }

}

The result is the xmllines array.

Hope this helps.

Comments

0

Try this

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

    System.out.println(node.getAttributes().getNamedItem("name"));
    System.out.println(node.getAttributes().getNamedItem("status"));

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.