【发布时间】:2010-04-10 07:10:25
【问题描述】:
我有一个类似html的xml,基本上就是html。我需要获取每个 .每个元素如下所示:
<line tid="744476117"> <attr>1414</attr> <attr>31</attr><attr class="thread_title">title1</attr><attr>author1</attr><attr>date1</attr></line>
我的代码如下,它确实识别出文件中有50个,但是在解析NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("attr");时它给了我NULLPointException
知道为什么会这样吗?相同的代码已用于其他应用程序而没有问题。
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(cleanxml));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("line");
for (int s = 0; s < nodeLst.getLength(); s++) {
System.out.println(nodeLst.getLength());
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("attr");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("attr : " + ((Node) fstNm.item(0)).getNodeValue());
}
}
【问题讨论】: