XML解析
一、 XML解析方式分为 dom sax 两种
a) 实现原理
i. Dom 实现的原理是整个xml文档一次性独处,放在一个属性结构里,在需要的时候,查找特定借点,然后对借点进行读或写。 优 实现简单。 缺 比较占内存
ii. Sax 只在xml文档中查找特定条件的内容,并且只提取需要的内容,这样做占内存小,灵活,它的缺点是就是写。只能读取,不能写。
b) XML解析器 Crimson、Xerces、Aelfred2
c) 开发工具包 Jaxp Jdpmdpm4j
i. Jaxp 由javax。xml org.w3c.dom org.xml.sax 包及子包组成
ii. 编写java程序完成xml文档的解析 dom解析器 用javax.xml.parsers包下的类来创建对象。
1. DocumentBuilder的对象是dom解析器 通过对应的工厂类创建 DocumentBuilderFactory. Factory=DocumentBuilderFactory.newInstance();
DocumentBuilderdb=factory.newDocumentBuilder();
对xml文档进行相应的解析
导入包 or。w3c、dom
C
Db.parse(new File(”src/book.xm”l));
//可以用反射机制来实现获取DocumentBuilder
解析内部的内容
Xml文档它里面所有的内容都会被当成 Node类型处理。 Element元素节点 Text文本节点,attr 属性节点
Org.w3c.dom Node类。 处理节点 节点类型
appendChild(Node newCharild)添加到此末尾一个新的节点
getNodeValue() 元素节点为空。 文本节点为文本
getNodeName() 得到该节点的名称 元素节点返回名称
getNodeType() 得到该节点的类型
事例代码:
//生成一个工厂模式对象
DocumentBuilderFactory.Factory=DocumentBuilderFactory.newInstance();
生成解析器对象
DocumentBuilderdb=factory.newDocumentBuilder();
对xml进行解析
Document doc =Db.parse(newFile(”src/book.xm”l));
//输出文档对象的子节点的个数 共有一个节点,根节点
findCharildren(doc); //Node是Document的接口
//System.out.println(Doc.getChildNodes().getLength());
//获取他的第一个子节点
//Noderoot=doc.getChildNodes().item(0);
//输入根节点的名字类型和值
//System.out.println(root.getNodeName+” ” //root.getNodeType()+” ”+root.getNodeValue());
Public static voidfindCharildren(Document doc){
//先通过文档对象doc得到根节点对象
Node root=NodeDoc.getElement ByTagName(“书架”).item(0);//根据名字查找节点,返回第一个 根节点
//通过root对象得到根节点的所有儿子节点,返回一个节点的集合
NodeListlist=root.getChildNodes();
System.out.println(list.length());//输出子节点个数
For(inti=0;iNode n=list.item(i);
System.out.println(n.getNodeName()+” ”+n.getNodeType()+” ”+n.getNodeValue());
}
}
//定义方法,找到指定元素中子元素的名字相同的第二个元子素
Public static voidfindFixedChild(Node node){
NodeListlist=node.getChildNodes();
Int count=0;
For(int i=0;i Boolean flag=false;
Node n1=list.item(i);
If(n1.getNodeName().equals(“书”)){
Flag=true;
Count++;
}
If(flag && count==2){
NodeListlist1=n1.getChildNodes();
For(intj=0;j Noden2=list1.item(j);
System.out.println(n2.getNodeName()+” ”+n2.getNodeType()+” ”+n2.getNodeValue());
}
}
}
}
//遍历属性节点
Public static voidfindAttibutes(Node node){
NameNodeMap map=node.getAttributes();
If(map!=null){
For(inti<0;i Noded&#61;map.item(i);
System.out.println(d.getNodeName()&#43;” ”&#43;d.getNodeType()&#43;” ”&#43;d.getNodeValue());
}
}
}
2. SAXParsers的对象是sax解析器 通过对象的工厂类创建