Java Android中的XML解析问题
这是我的XMLJava Android中的XML解析问题,java,xml,dom,xml-parsing,Java,Xml,Dom,Xml Parsing,这是我的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"
<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"));
}
stringxml=parser.getXmlFromUrl(url);//从给定URL获取XML
Document doc=parser.getdoElement(xml);//获取DOM元素
NodeList nl=doc.getElementsByTagName(“产品”);
//循环通过所有项目节点
对于(int i=0;i<10;i++){
元素e=(元素)nl.第(i)项;
//将每个子节点添加到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());
}
Element e=(Element)nl.第(i)项;
NamedNodeMap attributes=e.getAttributes();
对于(int a=0;a
循环运行了10次,比xml中的节点多,这就是为什么会出现空指针异常。尝试nl.length
(使用一个函数返回列表的lenth)以获取通过doc.getElementsByTagName(“产品”);生成的元素列表中的元素数代码>问题在于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);
选中此复选框,请为(inti=0;ivalue Log.v(“test”,e.getAttribute(“name”);}在code
NamedNodeMap attributes=e.getAttributes()处获取空指针异常;你能告诉我控制台打印e.getNodeName()得到了什么吗?现在我在这一行遇到了异常,如果我尝试此操作,请检查此链接。我成功地解析了xml节点的属性。