运行代码如下
package com.imooc.dmtest.test;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
try {
Document document=db.parse("books.xml");
NodeList bookList=document.getElementsByTagName("book");
System.out.println(bookList.getLength()+"本书");
for(int i=0;i<bookList.getLength();i++)
{
Node book = (Node) bookList.item(i);
NamedNodeMap attrs=book.getAttributes();
System.out.println("共有几个节点"+attrs.getLength());
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
显示出错,不知道为什么?
还有你的xml文件也贴出来
贴报错日志出来啊 不然怎么知道你哪里错了
报的什么错误,贴出来看看