这是我的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
谁能指出我在这里做错了什么?
答案 0 :(得分: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());
}
答案 1 :(得分:1)
循环运行10次,这比xml中存在的节点多,这就是你得到空指针异常的原因。尝试nl.length
(使用将返回列表长度的函数)以获取通过doc.getElementsByTagName("product");.
答案 2 :(得分: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);