一、JAXP、DOM介绍
JAXP:Java API for XML Programing
DOM:Document Object Method
DOM特点:
(1)将XML文档全部放入内存进行解析,因此耗内存;
(2)能够对XML进行增删改查;
<person> <name>xiazdong</name> <age>20</age> </person>
变成DOM树:
二、DOM API
DOM常用的类有:DocumentBuilderFactory、DocumentBuilder、Document、Node、NodeList、Element、Attribute、TransformerFactory、Transformer、DOMSource、StreamResult等类;
DOM开发步骤:
(1)通过DocumentBuilderFactory获得DocumentBuilder;
(2)通过DocumentBuilder解析XML,并获得Document(文档的根节点);
(3)通过Document进行操作;
(4)如果对XML进行了改动,则需要TransformerFactory创建一个Transformer;
(5)通过Transformer进行保存;
常用操作
DocumentBuilderFactory类中有:
(1)DocumentBuilderFactory factory =DocumentBuilderFactory .newInstance();
(2)DocumentBuilder builder = factory.newDocumentBuilder();
DocumentBuilder类中有:
(1)Document document = builder.parse(new File(""));//解析XML并返回document节点
(2)Document document = builder.newDocument(); //创建一个文档
Document类中有:
(1)NodeList list = getElementsByTagName("name");//获得<name>标签的队列
(2)Element e = document.createElement("name"); //创建一个<name>标签,并返回
NodeList类中有:
(1)Node node = nodeList.item(i); //获得节点队列的第i+1个节点
(2)int length = nodeList.getLength(); //获得节点队列的长度
Node中有:
(1)String text = node.getTextContent(); //获得节点的值
(2)node.appendChild(Node child); //向node尾部添加一个child子节点
(3)node.insertBefore(Node child,Node beforeNode);//向node的beforeNode子节点之前添加一个child子节点
(4)NodeList list = node.getChildNodes(); //获得node全部的子节点
(5)Node parent = node.getParentNode(); //获得node的父节点
(6)node.removeChild(Node child); //移除node的child子节点
(7)node.setTextContent(String text); //设置node 的值
(8)String name = node.getNodeName(); //获得标签的名称
Element中有:
(1)element.setAttribute("name","value"); //设置标签的属性
(2)String value = element.getAttribute("name"); //获得标签的属性
(3)element.removeAttribute("name") //移除标签的属性
TranformerFactory 中有:
(1)TransformerFactory tfactory = TransformerFactory.newInstance();
(2)Transformer tf = tfactory.newTransformer();
Transformer中有:
(1)tf.transform(Source source,Result result); //输出
DOMSource中有:
(1)DOMSource source = new DOMSource(Document document);
StreamResult中有:
(1)StreamResult result = new StreamResult(new FileOutputStream("1.xml"));
三、DOM进行CRUD
1.Create
private static void insert(Document document)throws Exception { Node person = document.getElementsByTagName("person").item(0); Node name = document.getElementsByTagName("name").item(0); Element tmp = document.createElement("tmpChild"); tmp.setTextContent("xxx"); person.insertBefore(tmp, name); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("1.xml"))); }
2.Read
应用:遍历整个XML文档并输出