public class DomDemo { public static void main(String[] args) { //创建解析的XML文档对象,其保存在工程根目录下的article.xml文件 File xmlFile = new File("/Users/Leonpard/Workspaces/MyEclipse 10/XMLprocess/WebRoot/article.xml"); //声明一个DocumentBuilder对象。抽象类,不能直接构建,可以通过DocumentFactory来构建 DocumentBuilder builder = null; //声明一个DocumentBuilderFactory对象。通过单例模式构建 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); try { builder = builderFactory.newDocumentBuilder(); //取得默认的DocumentBuilder Document document = builder.parse(xmlFile); //解析文件 Element root = document.getDocumentElement(); //获得根元素 System.out.println("根元素:" + root.getNodeName()); NodeList childNodes = root.getChildNodes(); //获得根元素下的子节点 for(int i = 0; i < childNodes.getLength(); i ++) { //遍历子节点 Node node = childNodes.item(i); if("article".equals(node.getNodeName())) { //如果节点名称为"article" //输出article元素属性category System.out.println("\r\n找到一篇文章。所属分类:" + node.getAttributes().getNamedItem("category") .getNodeValue() + "。"); //获得article下的节点 NodeList nodeDetail = node.getChildNodes(); for(int j = 0; j < nodeDetail.getLength(); j ++) { Node detail = childNodes.item(j); if("title".equals(detail.getNodeName())) { System.out.println("标题:" + detail.getTextContent()); } else if("author".equals(detail.getNodeName())) { System.out.println("作者:" + detail.getTextContent()); } else if("email".equals(detail.getNodeName())) { System.out.println("邮箱:" + detail.getTextContent()); } else if("date".equals(detail.getNodeName())) { System.out.println("日期:" + detail.getTextContent()); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 、、、
if("title".equals(detail.getNodeName())) {
这里为什么抛出空指针异常??
When detail is null, isn’t it a null pointer?
detail can be null detail.getNodeName() can also be null