package test_XML; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOM_XML_Test { public static void main(String[] args){ try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db =dbf.newDocumentBuilder(); Document document = db.parse("book.xml"); NodeList bookList = document.getElementsByTagName("book"); System.out.println("咱们书店共有"+bookList.getLength()+"本书"); for(int i=0;i<bookList.getLength();i++){ System.out.println("下面开始遍历第"+(i+1)+"本书的内容"); Node book = bookList.item(i); NamedNodeMap attributes=book.getAttributes(); System.out.println("第"+(i+1)+"本书共有"+attributes.getLength()+"个属性"); for(int j=0; i<attributes.getLength();j++){ Node attr = attributes.item(j); System.out.print("属性名"+attr.getNodeName()); System.out.print("属性值"+(String)attr.getNodeValue()); } } } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } }
找半天没看明白怎么就有空指针异常了呢?
打断点调试一下,是不是bookList就是空的
<?xml version="1.0"encoding="UTF-8"?> <bookstore> <book id="1"> <name>冰与火之歌</name> <author>乔治马丁</author> <year>2014</year> <price>22</price> </book> <book id="2"> <name>飘</name> <author>米切尔</author> <price>99</price> <language>English</language> </book> </bookstore>
就在哪个get属性名和属性值的地方 提示有空指针异常 没明白。。。