0

这是我的 XML。

 <results keywords="ipod" limit="25">
   <products count="30">
     <product merchant_price="179.99" 
       network_id="2" 
       name = "ipod" 
       retail_price="179.99" />
     <product merchant_price="189.99" 
       network_id="3"
       name="ipod16gb" 
       retail_price="189.99" />
   </products>
</results>

由此我需要单独获取产品属性。为此,我已经这样做了,我编写了一个解析器。

String xml = parser.getXmlFromUrl(url); // getting XML from the given URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("product");
// looping through all item nodes 
for (int i = 0; i < 10; i++) {
    Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
    Log.v("test",e.getAttribute("name"));
    }

但是我无法正确获得价值并获得 NullPointerException 任何人都可以指出我在这里做错了什么吗?

4

3 回答 3

1

尝试一下

     Element e = (Element) nl.item(i);
     NamedNodeMap attributes = e.getAttributes();
            for (int a = 0; a < attributes.getLength(); a++) 
       {
            Node theAttribute = attributes.item(a);
          System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
        }
于 2012-10-04T11:43:27.357 回答
1

循环运行 10 次,比 xml 中存在的节点多,这就是为什么你得到空指针异常。尝试nl.length(使用将返回列表长度的函数)获取您通过的元素列表中的元素数量doc.getElementsByTagName("product");.

于 2012-10-04T11:52:55.263 回答
0

问题出在 Xml 解析器上。在解析时对此进行了更正。

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
于 2012-10-04T13:08:35.673 回答