DOM解析
实例:
public class ParseDOM {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder对象
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//通过document对象的parse方法加载roles.xml到当前项目下
Document document = db.parse("books.xml");
NodeList bookList = document.getElementsByTagName("book");
System.out.println("一共有"+bookList.getLength()+"本书");
//遍历book节点
for(int i=0 ; i<bookList.getLength();i++){
//通过item(i)方法获取一个book节点,nodeList的索引从0开始
System.out.println("================开始遍历第"+(i+1)+"本==================");
Node book = bookList.item(i);
//获取该节点所有属性
NamedNodeMap attrs = book.getAttributes();
//遍历book节点属性
System.out.println("一共"+attrs.getLength()+"个属性");
for(int j=0; j<attrs.getLength();j++){
//获取一个节点属性
Node attr = attrs.item(j);
System.out.print("属性名:"+attr.getNodeName());
System.out.println("--属性值:"+attr.getNodeValue());
}
// Element book = (Element) bookList.item(i);
// String attrValue = book.getAttribute("id");
// System.out.println("id属性的属性值为"+attrValue);
//解析book节点的子节点
NodeList childnotes = book.getChildNodes();
System.out.println("第"+(i+1)+"本书共有"+childnotes.getLength()+"个子节点");
//遍历book下的子节点
for(int k=0;k<childnotes.getLength();k++){
Node child = childnotes.item(k);
if(childnotes.item(k).getNodeType() == Node.ELEMENT_NODE){
System.out.print("子节点属性名为:"+child.getNodeName());
// System.out.println("--子节点属性值为:"+child.getFirstChild().getNodeValue());
System.out.println("--子节点属性值为:"+child.getTextContent());
}
}
System.out.println("================结束遍历第"+(i+1)+"本==================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<year>2004</year>
<price>78</price>
<language>English</language>
</book>
</bookstore>