码迷,mamicode.com
首页 > 其他好文 > 详细

DOM4J

时间:2015-07-02 00:51:50      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

package com.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import java.util.List;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class Dom4jDemo {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        SAXReader sr = new SAXReader();
        Document doc = sr.read("webroot/NewFile.xml");
        delete(doc);
        list(doc.getRootElement());
    }
    
    public static void delete(Document doc) throws Exception{
        Element e = (Element) doc.getRootElement().elements("计算机书籍").get(3);
        //e.getParent().remove(e);
        
        //删除作者的电话
        e.element("作者").remove(e.element("作者").attribute("phone"));
        //更新xml,更新后硬盘上的XML才会有变化
        OutputFormat of = org.dom4j.io.OutputFormat.createPrettyPrint();
        of.setEncoding("utf-8");
        XMLWriter xw = new XMLWriter(new FileOutputStream("webroot/NewFile.xml"),of);
        xw.write(doc);
        xw.close();
    }
    
    
    
    public static void add(Document doc) throws Exception{
        //DocumentHelper这个类有一个静态方法可以创造element
        Element e = DocumentHelper.createElement("计算机书籍");
        Element e1= DocumentHelper.createElement("书名");
        e1.setText("hzz‘s book");
        Element e2= DocumentHelper.createElement("价格");
        Element e3= DocumentHelper.createElement("作者");
        e2.setText("110");
        e3.setText("HZZ");
        e3.addAttribute("hobby", "joking");
        e.add(e1);
        e.add(e2);
        e.add(e3);
        doc.getRootElement().add(e);
        
        OutputFormat of = org.dom4j.io.OutputFormat.createPrettyPrint();
        of.setEncoding("utf-8");
        XMLWriter xw = new XMLWriter(new FileOutputStream("webroot/NewFile.xml"),of);
        xw.write(doc);
        xw.close();
    }
    
    public static void read(Document doc){
        Element e = doc.getRootElement();
        Element e2=(Element) e.elements("计算机书籍").get(0);
        System.out.println(e2.element("书名").getText());
        System.out.println(e2.element("作者").getText());
        System.out.println(e2.element("作者").attributeValue("phone"));

    }
    
    public static void list(Element e){
        System.out.println(e.getName()+e.getTextTrim());
        Iterator it = e.elementIterator();
        while(it.hasNext()){
            Element e2 = (Element) it.next();
            list(e2);
        }
        
    }
    

}

 

DOM4J

标签:

原文地址:http://www.cnblogs.com/hzzhero/p/4614880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!