开发者

Parsing xml document in java

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++)
      开发者_如何学Python         {  
                   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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜