一、Java中操作DOM中常用的类
- Node
数据类型基类
- Element
最常用的类
- Attr
Element的属性
- Text
Element or Attr的内容
- Document
代表整个XML文档,代表DOM tree
二、xml文件
<?xml version = "1.0" encoding = "utf-8"?>
<books>
<book id="1">
<name>冰与火之歌</name>
<author>张三</author>
<pice>99</pice>
</book>
<book id="2">
<name>葫芦娃</name>
<pice>99</pice>
<year>1993</year>
</book>
</books>
三、Dom解析XML案例Demo
package com.da.dom;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomTest {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory对象
DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
try {
//创建DocumentBuilder对象
DocumentBuilder db = documentBuilder.newDocumentBuilder();
//通过DocumentBuilder中的parse方法加载book。xml文件到当前项目下
Document document = db.parse("books.xml");
//获取所有book节点的集合
NodeList nodeList = document.getElementsByTagName("book");
//遍历每个book节点
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println("==========第"+(i+1)+"本==========");
// Node book = nodeList.item(i);
// NamedNodeMap attributes = book.getAttributes();
// //不知道当前节点下有多少参数属性值
// for (int j = 0; j < attributes.getLength(); j++) {
// Node item = attributes.item(j);
// System.out.print("获取属性名:"+item.getNodeName());
// System.out.println("获取属性值:"+item.getNodeValue());
// }
//确切当前参数下有多少参数属性值
Element element = (Element) nodeList.item(i);
System.out.println("id值:"+element.getAttribute("id"));
//获取book下面的子节点
NodeList childNodes = nodeList.item(i).getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
System.out.print(childNodes.item(j).getNodeName()+":");
System.out.println(childNodes.item(j).getTextContent());
};
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}