[英]Issue in XML parsing in Android
這是我的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
任何人都可以指出我在這里做錯了什么?
試試吧
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());
}
循環運行10次,這比你的xml中存在的節點多,這就是你得到空指針異常的原因。 嘗試使用nl.length
(使用將返回列表長度的函數)來獲取通過doc.getElementsByTagName("product");.
的元素列表中的元素數量doc.getElementsByTagName("product");.
問題出在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.