DOM模型介绍
bject Model:文档对象模型
Dom解析方法:xml文件解析首先将xml文件加载进内存,然后读取文件中的内容。
在内存将文件以树的结构进行保存,而且树根在上,树枝在下,整个xml文件被封装为
Document对象,文件中的标签节点被封装为Node对象,标签节点中保存的数据被封装为
Text对象。
DOM模型将整个xml文件封装为对象,将文件中的标签和数据封装为对象,利用对象提供的方法完成xml文件内容的读写。
Document: 表示整个文件对象
Node:表示标签对象
Text:表示标签中的数据内容
JDK提供的解析方法。
创建studentes.xml文件
使用Dom解析studentes.xml
Dom解析API总结:
DocumentBuilderFactory: 解析工厂对象
DocumentBuilder: 解析器对象
Document: 文档对象,封装了内存中的dom树
NodeList: dom树种某个节点的所有子节点集合
Node:dom树种的一个节点
Element : Node的子接口,对Node功能进行扩展。
文档的兼容性差,文档的结构发生变化,解析代码就可能变化
Dom解析的性能差(文件比较大的时候),一次性将整个文档加载进内存。
Dom解析的使用java自身的一些类或者框架平台。
代码实现:
public class DomParseXml {
public static void main(String[] args) {
try {
/****
* 实现将studentes.xml解析,读取文件中的内容
*/
//1 创建DocumentBuilderFactory对象,可以获得dom树的解析器
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
//2 创建通过工程对象,创建DocumentBuilder对象
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
//3 创建File对象,封装需要解析的xml文件
File f=new File("D:\\eclipse-work\\12_09_day18\\src\\studentes.xml");
//4 将文件加载进内容,产生dom树对象,获得了需要解析的xml文件对象
Document document = documentBuilder.parse(f);
//获得document对象的所有子节点
NodeList childNodes = document.getChildNodes();
System.out.println("length===="+childNodes.getLength());
//获得childNodes集合中的一个节点,文档中的根节点
Node studentes = childNodes.item(0);
//获得node节点的名字
String nodeName = studentes.getNodeName();
//获得node节点的类型(1 元素节点(标签) 3 表示文本节点有值的)
short nodeType = studentes.getNodeType();
//3获得node节点的value(null)
String nodeValue = studentes.getNodeValue();
System.out.println(nodeName+"\t"+nodeType+"\t"+nodeValue);
//获得studentes的子节点,有文档结构的兼容性问题,dom认为空的换行也是节点
NodeList student = studentes.getChildNodes();
//遍历studentes的子节点
for(int x=0;x<student.getLength();x++) {
Node n=student.item(x);
//判断当前遍历的节点是否为空的换行节点
if(n.getNodeType()!=3) {
//System.out.println(n.getNodeType()+"\t"+n.getNodeName());
//获得n标签的id属性的值
Element e=(Element)n;
String id = e.getAttribute("id");
System.out.print(id+"\t");
//获得n表示的student的所有子节点
NodeList info = n.getChildNodes();
//System.out.println(info.getLength());
//遍历info及节点对象集合,遍历出来的是学生的信息的标签
for(int y=0;y<info.getLength();y++) {
Node d=info.item(y);
if(d.getNodeType()!=3) {
//System.out.println(d.getNodeType()+"\t"+d.getNodeName());
//获得标签中间的内容
String value = d.getTextContent();
System.out.print(value+"\t");
}
}
//换行
System.out.println();
}