简体   繁体   English

用Java解析XML文档

[英]Parsing xml document in java

I am trying to retrieve some data from xml document, but the program throws NullPointerException. 我试图从xml文档中检索一些数据,但是程序抛出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. 由于item(0)方法中的index值引发异常。 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. 我有类似的程序解析XML文档,它会引发异常(NullPOinter),但仍会运行,因为我捕获了异常。 The same thing I am trying to do here, but the program does not work, terminates, though I catch Exception. 我在这里尝试执行相同的操作,但是该程序无法运行,但是终止,尽管我捕获了Exception。 How to extract correct index for item() method? 如何为item()方法提取正确的索引? Cheers 干杯

getChildNodes().item(0)

getChildNodes() returns a NodeList ; getChildNodes()返回一个NodeList use this value and check that its length is greater than zero. 使用此值并检查其长度是否大于零。

NullPointerException s are an indication of a programming error and should not be caught. NullPointerException表示编程错误,不应捕获。


As an aside, you may want to look at the XPath API for extracting data from DOM trees. 顺便说一句,您可能希望查看用于从DOM树提取数据的XPath API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM