Dom解析(增删改查)

xml文档:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><persons>
<person>
<name>wuyihua</name>
<grade>98</grade>
<id>1</id></person>
<person job="student">
<name>zengxiangjian</name>
<grade>100</grade>
<id>3</id></person>
</persons>





package com.dom.domain;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Domparse {
private Document doc;
@Test
public void parseXml() throws Exception {//解析xml的的方法
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 得到解析工厂
DocumentBuilder builder = factory.newDocumentBuilder();
   doc = builder.parse("src/person.xml");
}
@Test
public void read() throws Exception {//读取指定的节点,并打印出名字
parseXml();
Node node = doc.getElementsByTagName("person").item(0);
System.out.println(node.getNodeName());
}
@Test
public void ListAll() throws Exception {//列出所有节点的方法
parseXml();
NodeList personsNode = doc.getElementsByTagName("persons");
list(personsNode);
}
public void list(NodeList list) {//用来递归获取子节点的方法
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
System.out.println(node.getNodeName());
NodeList nodelist = node.getChildNodes();
list(nodelist);
}
}
@Test
    public void addElement() throws Exception{//添加子节点,并为子节点设置名字和属性
parseXml();
    Node node=doc.getElementsByTagName("person").item(0);
    Element price=doc.createElement("price");
    price.setAttribute("hello", "world");
    price.setTextContent("100");
    node.appendChild(price);
    write2Xml();
    }
@Test
public void Delete() throws Exception{//删除节点,先获取指定的节点,然后获取父节点,再删除自己;
parseXml();
Node childNode=doc.getElementsByTagName("price").item(0);
Node parentNode=childNode.getParentNode();
parentNode.removeChild(childNode);
write2Xml();
}
@Test
    public void write2Xml() throws Exception{//将变更后的文档写入person.xml的方法
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer tf=factory.newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult("src/person.xml"));
   
    }
}

你可能感兴趣的:(xml,dom,element,node)