我在android中解析XML时遇到异常
代码是我在android中解析XML时遇到异常,android,xml,xml-parsing,Android,Xml,Xml Parsing,代码是 /// Element rootelement = doc.getDocumentElement(); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); try { xpathexpression = xpath.compile("//@*[name()='diffgr:id']");
/// Element rootelement = doc.getDocumentElement();
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
try {
xpathexpression = xpath.compile("//@*[name()='diffgr:id']");
result = xpathexpression.evaluate(doc,XPathConstants.NODESET);
Log.v(result.toString(), "Value of result");
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NodeList nodelist =(NodeList) result;
Node childlist = null;
// org.w3c.dom.Element rootelement = doc.getDocumentElement();
// NodeList nl = rootelement.getChildNodes();
Log.v(new Integer(nodelist.getLength()).toString(), "Lenght of node list");
for (int i =0; i< nodelist.getLength(); i++)
{
Node n = nodelist.item(i);
System.out.println("message");
childlist = n.getFirstChild();
System.out.println("message2");
String s = childlist.getNodeValue(); // THIS LINE GIVES EXCEPTION ELSE CODE IS CORRECT
如果以下行导致NullPointerException,则childlist可能为null
String s = childlist.getNodeValue();
如果以下调用返回null,则对象childlist为null
childlist = n.getFirstChild();
如果n指向的对应xml节点中没有子节点,则类节点的方法getFirstChild()将导致null。比较两种方法。因此,您应该检查xml节点n指向哪个节点,以及这个节点是否有child。为了得到更好的答案,我想您必须给出一个解析xml文档的示例
childlist = n.getFirstChild();