//在下纯给自己做笔记,抱歉。
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<bookstore>
<book id="1">
<name><a>aa</a>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<year>2004</year>
<price>77</price>
<language>English</language>
</book>
</bookstore>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domtest;
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;
/**
*
* @author Administrator
*/
public class DomTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO code application logic here
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document document=db.parse("newXMLDocument.xml");
//获取所有book节点的集合
NodeList bookList=document.getElementsByTagName("book");
System.out.println(bookList.getLength());
//遍历每一个book节点
for(int i=0;i<bookList.getLength();i++){
System.out.println("下面开始遍历第"+(i+1)+"本书的内容");
//通过获取一个book节点
Node book=bookList.item(i);
//获取book节点的所有属性的集合
NamedNodeMap attrs=book.getAttributes();
System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
for(int j=0;j<attrs.getLength();j++){
//通过item()方法获取某一个属性
Node attr=attrs.item(j);
//获取属性名
System.out.println("属性名:"+attr.getNodeName());
//获取属性值
System.out.println("属性值:"+attr.getNodeValue());
}
/*Element book=(Element)bookList.item(i);
String attrValue=book.getAttribute("id");
System.out.println("id属性的属性值为:"+attrValue);*/
NodeList childNodes=book.getChildNodes();
//遍历childNodes获取每个节点的节点名和节点值
System.out.println("第"+(i+1)+"本书共有"+childNodes.getLength()+"个子节点");
for(int k=0;k<childNodes.getLength();k++){
//区分出text类型的node以及element类型的node
if(childNodes.item(k).getNodeType()==Node.ELEMENT_NODE){
System.out.println("第"+(k+1)+"个节点名:"+childNodes.item(k).getNodeName());
System.out.println("第"+(k+1)+"个节点的节点值:"+childNodes.item(k).getTextContent());
}
}
System.out.println("======================结束遍历第"+(i+1)+"本书==========================");
}
}
}