DOM4J_SIMPLE_DEMO

简单小记:DEMO见附件

 

package test;

import java.io.FileWriter;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4JTest {
    
    public static void main(String[] args) throws Exception{
        
        DOM4JTest test = new DOM4JTest();
        
        //step 1
        Document doc = test.parseDocument(new URL("file:applicationContext.xml"));
        //step 2-1
//        test.usingIterator1(doc);
        //step 2-2
//        test.usingIterator2(doc);
        //step 2-3
//        test.usingIterator3(doc);
        //step 2-4
//        test.elements(doc);
        //step 3-1
//        test.xpath1(doc);
        //step 3-2
//        test.xpath2(doc);
        //step 4
//        test.treeWalker(doc.getRootElement());
        //step 5 
//        Document d = test.create();
//        test.treeWalker(d.getRootElement());
        //step 6-1
//        test.output1(test.create());
        //step 6-2
//        test.output2(test.create());
        //step 6-3
//        test.output3(test.create());
        //step 7-1
//        test.convert1(doc);
        //step 7-2
//        test.convert2();
        //step 8
        test.insert(doc);
    }
    
    //解析document----new SAXReader().read(URL)
    public Document parseDocument(URL url) throws Exception{
        //SAX=Simple Api for XML
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
    //遍历子元素iterator------element.elementIterator
    public void usingIterator1(Document document){
        Element root = document.getRootElement();
        System.out.println(root.getName());
        Iterator iterator = root.elementIterator();
        while(iterator.hasNext()){
            Element element = (Element)iterator.next();
            //相对于根[/]的path===>return /beans/bean
            System.out.println(element.getPath());
            //相对于参数Element元素的path
            System.out.println(element.getPath(root.getParent()));
            System.out.println(element.getName());
            System.out.println("#################################");
        }
    }
    //根据name-标签名遍历子元素---element.elementIterator(name)
    public void usingIterator2(Document document){
        Element root = document.getRootElement();
        //遍历name=param的所有子元素
        Iterator iterator = root.elementIterator("test2");
        while(iterator.hasNext()){
            Element element = (Element)iterator.next();
            System.out.println(element.getName());
            System.out.println("#################################");
        }
    }
    //遍历元素的属性---element.attributeIterator(name)
    public void usingIterator3(Document document){
        Element root = document.getRootElement();
        //遍历name=param的所有子元素
        Iterator iterator = root.elements().get(0).attributeIterator();
        while(iterator.hasNext()){
            Attribute attribute = (Attribute)iterator.next();
            System.out.println(attribute.getName());
            System.out.println(attribute.getData());
            System.out.println(attribute.getPath());
            System.out.println(attribute.getText());
            System.out.println("#################################");
        }
    }
    //列表LIST遍历
    public void elements(Document document){
        
//        List elements = document.getRootElement().elements("bean");
        List elements = document.getRootElement().elements();
        for(Object obj : elements){
            System.out.println(((Element)obj).getName());
        }
    }
    //xpath的支持需要xpath库-jaxen.jar
    //XPATH----List list = document.selectNodes(//path)
    public void xpath1(Document document){
        //xpath接口用法-
//        XPath xpathSelector = DocumentHelper.createXPath("//beans/test1");
//        List list = xpathSelector.selectNodes(document);
        List list = document.selectNodes("//beans/test1");
        for(Object obj : list){
            Element element = (Element)obj;
            System.out.println(element.getName());
        }
        System.out.println("#####################################################");
        //xpath-属性选择
        list = document.selectNodes("//beans/test1[@id!='userService1']");
        for(Object obj : list){
            Element element = (Element)obj;
            System.out.println(element.valueOf("@id"));
        }
        System.out.println("#####################################################");
        //xpath-序号选择####序号从1开始
        list = document.selectNodes("//beans/test1[@id!='userService1'][2]");
        for(Object obj : list){
            Element element = (Element)obj;
            System.out.println(element.valueOf("@id"));
        }
    }
    //XPATH----selectSingleNode|node.valueOf("@attributeName")
    public void xpath2(Document document){
        Node node = document.selectSingleNode("//beans");
        System.out.println(node.getName());
        System.out.println("#####################################################");
        //selectSingleNode仅选择一个Node,若有多个并列的Node,则选择第一个
        node = document.selectSingleNode("//beans/bean");
        System.out.println(node.valueOf("@class"));
    }
    //递归遍历
    public void treeWalker(Element element){
        for(int i = 0;i < element.nodeCount();i++){
            Node node = element.node(i);
            System.out.println(node.getPath());
            if(node instanceof Element){
                treeWalker((Element)node);
            }
        }
    }
    //创建XML
    public Document create(){
        
        //或DocumentHelper.createDocument(空)==>建立无根document,再add
        Element root = DocumentHelper.createElement("xmlRoot")
                        .addAttribute("hehe", "ai");
        Document document = DocumentHelper.createDocument(root);
        //链式!!!
        Element author1 = root.addElement("author")
                            .addAttribute("name", "haimingwei")
                            .addAttribute("age", "dead")
                            .addAttribute("gender", "male")
                            .addText("author1_text");
        Element author2 = root.addElement("author")
        .addAttribute("name", "seven")
        .addAttribute("age", "100")
        .addAttribute("gender", "male")
        .addText("author2_text");
        
        return document;
    }
    //output
    public void output1(Document document) throws Exception{
        FileWriter fw = new FileWriter("dom4j_text.xml");
        document.write(fw);
        //不close竟然输出文件中没有内容
        fw.close();
    }
    //output-format
    public void output2(Document document) throws Exception{
        //compact紧凑格式
        //OutputFormat format = OutputFormat.createCompactFormat();
        //漂亮格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter("dom4j_text.xml"),format);
        writer.write(document);
        writer.close();
    }
    //output-输出到console
    public void output3(Document document) throws Exception{
        //compact紧凑格式
        //OutputFormat format = OutputFormat.createCompactFormat();
        //漂亮格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //OutputFormat可设置编码
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(System.out,format);
        writer.write(document);
        writer.close();
    }
    //Document===>String
    public void convert1(Document document){
        String xmlStr = document.asXML();
        System.out.println(xmlStr);
    }
    //String===>Document[DocumentHelper.parseText]
    public void convert2() throws Exception{
        String xmlStr = "<bean id=\"dataSource\" class=\"org.springframework.jdbc.datasource.DriverManagerDataSource\">" +
                        "<property name=\"driverClassName\" value=\"com.mysql.jdbc.Driver\"/>" +
                        "<property name=\"url\" value=\"jdbc:mysql://localhost:3306/frame\"/>" +
                        "<property name=\"username\" value=\"root\"/><property name=\"password\" value=\"\"/></bean>";
        Document doc = DocumentHelper.parseText(xmlStr);
        this.output3(doc);
    }
    //insert-复制[dom4j中clone为深克隆]一个元素并插入
    public void insert(Document document) throws Exception{
        
        Element element = document.getRootElement().elements().get(0);
        Element newElement = (Element)element.clone();
        
        //????content()
        List childList = element.getParent().elements();
        childList.add(element.getParent().indexOf(element),newElement);
        //重新写回XML文件  - -!
        XMLWriter writer = new XMLWriter(new FileWriter("applicationContext.xml"),new OutputFormat().createPrettyPrint());
        writer.write(document);
        writer.close();
    }
}

 

你可能感兴趣的:(simple)