0

I am trying to retrieve some data from xml document, but the program throws NullPointerException. This is the snippet of code:

     if("Success".equals(nodeValue))
     {

           NodeList productList = xmlDocument.getElementsByTagName("Products").item(0).getChildNodes(); // gets all childs of Product node
           for (int j = 0; j < productList.getLength(); j++)
           {
               singleProduct = xmlDocument.getElementsByTagName("Product").item(j).getChildNodes();

               for(int x = 0; x < singleProduct.getLength(); x++)
               {  
                   if(singleProduct.item(x).getNodeType() == Node.ELEMENT_NODE)
                   {
                   String nodeName = singleProduct.item(x).getNodeName();

                 String value = singleProduct.item(x).getChildNodes().item(0).getNodeValue();
                         System.err.println(x+" "+nodeName+" "+ value);
                     if ("ProductID".equals(nodeName))
                {

                    id.put(xx, value);
                        type.put(y, singleProduct.item(x).getChildNodes().item(1).getAttributes().getNamedItem("type").getTextContent());;
                    xx++;
                        y++;
                     }
                  }
               }
           }
     }

This part throws exception:

                 String value = singleProduct.item(x).getChildNodes().item(0).getNodeValue();

Exception is thrown due to the value of index inside item(0) method. How should I know the index of item in collection? I have similar program parsing XML document, it throws exception (NullPOinter) but still it runs because I catch exception. The same thing I am trying to do here, but the program does not work, terminates, though I catch Exception. How to extract correct index for item() method? Cheers

1 Answer 1

4
getChildNodes().item(0)

getChildNodes() returns a NodeList; use this value and check that its length is greater than zero.

NullPointerExceptions are an indication of a programming error and should not be caught.


As an aside, you may want to look at the XPath API for extracting data from DOM trees.

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

2 Comments

I checked the length, it is 1. What are other thoughts?
@ucas - it isn't obvious to me where the issue is based on the code sample. I can see some red flags - like calling xmlDocument.getElementsByTagName more than once, but without seeing a sample document and the ultimate goal, it is difficult to provide help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.