java: how to parse html-like xml
Posted
by Yang
on Stack Overflow
See other posts from Stack Overflow
or by Yang
Published on 2010-04-09T22:54:29Z
Indexed on
2010/04/09
23:13 UTC
Read the original article
Hit count: 212
I have an html-like xml, basically it is html. I need to get the elements in each . Each element looks like this:
<line tid="744476117"> <attr>1414</attr> <attr>31</attr><attr class="thread_title">title1</attr><attr>author1</attr><attr>date1</attr></line>
My code is as below, it does recognize that there are 50 in the file, but it gives me NULLPointException when parsing NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("attr");
Any idea why this is happening? The same code has been used for other applications without problems.
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());
}
}
© Stack Overflow or respective owner