xml解析之dom

程式碼修行者發表於2015-09-21
package cn.tong.jaxp;

import java.io.IOException;

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.TransformerException;
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.xml.sax.SAXException;

public class TestJaxp {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
        // 查詢所有name元素的值

        //建立解析器工程
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        //建立解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        //解析xml返回document
        Document document = builder.parse("src/person.xml");

        //得到name元素

        NodeList list = document.getElementsByTagName("name");

        for(int i = 0 ; i < list.getLength() ; i++){
            Node name1 = list.item(i);
            //得到name元素的值
            System.out.println(name1.getTextContent().toString());


        }

        NodeList p1  = document.getElementsByTagName("p1");
        for(int i = 0 ; i < p1.getLength() ; i++){
            Node p = p1.item(i);
            //得到name元素的值

            Element el_gender = document.createElement("gender");

            el_gender.setTextContent( i%2 == 0 ? "男" : "女" );

            p.appendChild(el_gender);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
}

相關文章