DOM4j的使用

package TEST;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4j implements XMLDocument{

public static void main(String[] args) {
    XMLDocument doc = new Dom4j();      //创建dom4j对象

// doc.creatXml("a.xml"); //调用creatXml()方法,将内容写到a.xml文件中

    doc.parseXml("a.xml");              //调用parseXml解析方法,解析a.xml文件
}


public void creatXml(String filename) {
    
    Document document = DocumentHelper.createDocument();    //创建xml文档,并加上头部
    Element users = document.addElement("users");   //添加根节点users
    Element user = users.addElement("user");        //在根节点下添加二级节点user
    Element name = user.addElement("name");         //在二级节点user下添加三级节点name
    name.setText("张三");                         //在三级节点name中加上内容
    user.addElement("age").setText("12");           //添加三级节点age,并加上内容
    user.addElement("sex").setText("男");            //添加三级节点sex,并机上内容
    user.addAttribute("id","001");                  //给user添加id属性
    
    System.out.println(document.asXML());           //打印xml文档
    
    Writer writer;
    try {

// writer = new FileWriter(filename);
// XMLWriter xmlwriter = new XMLWriter(writer);

        //包装流,创建字节输出流(utf-8格式,,解决字符集不匹配问题),再将字节输出流转成字符输出流
        OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(filename),Charset.forName("UTF-8"));
        XMLWriter xmlwriter = new XMLWriter(ow);    //创建XML文档写入流
        xmlwriter.write(document);                  //写入对象
        xmlwriter.close();                          //关闭流
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
}

@Override
public void parseXml(String filename) {
    SAXReader reader = new SAXReader();
    Document document;
    try {
        document = reader.read(new FileInputStream(filename));
        Element root = document.getRootElement();       //得到xml文档的根节点
        List elements = root.elements();       //得到根节点下的节点集合
        System.out.println("根节点下的节点总个数为:" + elements.size());
        for (Element e : elements) {        //输出根节点下的每个节点
            System.out.println(e.getName());
            e.elements().forEach((child)->{
                Element c = (Element) child;
                System.out.println("\t" + c.getName() + " : " + c.getText());   //输出根节点下的每个根节点和里面的内容
            });
        }
        
    } catch (FileNotFoundException | DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    
    
}

}

你可能感兴趣的:(DOM4j的使用)