xml文件 如下
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="156">
<name>计算机网络</name>
<author>谢希仁</author>
<price>39</price>
<year>2013</year>
</book>
<book id="234">
<name>计算机操作系统</name>
<author>佚名</author>
<price>40</price>
<year>2013</year>
<edition>第四版</edition>
</book>
<book id="367">
<name>计算机组成原理</name>
<price>35</price>
<year>2013</year>
<edition>第三版</edition>
</book>
</bookstore>
java代码如下
package test;
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.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlParser {
public static void main(String[] args) {
// 创建DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// 创建DocumentBuilder对象
DocumentBuilder docBulider = dbf.newDocumentBuilder();
// 创建Document对象,Document对象表示整个 HTML 或 XML 文档
Document document = docBulider.parse("book.xml");
// 获取book节点的集合
NodeList bookList = document.getElementsByTagName("book");
for (int i = 0; i < bookList.getLength(); i++) {
// Element是Node的子类,Node可以通过getAttributes() 方法遍历一个节点的全部属性
// 若要访问某个节点的具体的属性,只需将该节点强制类型转换成Element,使用getAttribute(String name) 即可
Element book = (Element) bookList.item(i);
// 获取书本的id
String id = book.getAttribute("id");
System.out.println("第" + (i + 1) + "本书的id是:" + id);
// 获取book节点的子节点
NodeList valueList = book.getChildNodes();
for (int j = 0; j < valueList.getLength(); j++) {
//Node节点可以是元素节点、属性节点、文本节点。
//Element表示XML文档中的元素
if (valueList.item(j) instanceof Element) {
String name = valueList.item(j).getNodeName();
// 获取属性值
String value = valueList.item(j).getTextContent();
System.out.println(name + "--" + value);
}
}
System.out.println("--------------------------------");
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
控制台输出结果如下
第1本书的id是:156
name--计算机网络
author--谢希仁
price--39
year--2013
--------------------------------
第2本书的id是:234
name--计算机操作系统
author--佚名
price--40
year--2013
edition--第四版
--------------------------------
第3本书的id是:367
name--计算机组成原理
price--35
year--2013
edition--第三版
--------------------------------
其中需要注意的是Element和Node区别:
Element是Node的子类
Node表示一个节点,可以是元素节点,属性节点,也可以是文本节点
Elemen表示xml文本中的元素,即<div></div>,<book></book>这些才算一个Element元素
Node可以通过getAttributes() 方法遍历一个节点的全部属性
若要访问某个节点的具体的属性,只需将该节点强制类型转换成Element,使用getAttribute(String name) 即可