代码改变世界

Java 使用jaxp添加节点

2016-12-12 11:24  甘雨路  阅读(366)  评论(0编辑  收藏  举报
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <p1>
        <name>jobs</name>
        <age>56</age>
    </p1>
    <p1>
        <name>Alis</name>
        <age>32</age>
    </p1>
</person>
package jaxp;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;







import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;


public class TestJaxp {
    public static void main(String[] args) {
        try {
            addSex();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void addSex() throws Exception{
        //创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        //解析xml返回document
        Document document = document = builder.parse("src/person.xml");
        
        // 得到所有的p1
        NodeList list = document.getElementsByTagName("p1");
        // 得到第一个p1
        Node p1 = list.item(0);
        // 创建标签
        Element sex = document.createElement("sex");
        //创建文本
        Text text = document.createTextNode("female");
        //把文本添加到sex下面
        sex.appendChild(text);
        // 把sex添加到p1下面
        p1.appendChild(sex);
        // 回写xml
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
    
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person>
    <p1>
        <name>jobs</name>
        <age>56</age>
        <sex>female</sex>
    </p1>
    <p1>
        <name>Alis</name>
        <age>32</age>
    </p1>
</person>