用DOM4J解析XML文件案例

用DOM4J解析XML文件案例,由于DOM4J不像JAXP属于JAVASE里,所以如果要使用DOM4J,则必须额外引入jar包,如图:

1.xml文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>

<class> 
  <student> 
    <name>张三</name>  
    <sid>111111</sid> 
  </student>  
  <student> 
    <name>李四</name>  
    <sid>222222</sid> 
  </student> 
</class>
复制代码

Java代码:

复制代码
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jCase {
    static Element root;
    public static void main(String[] args) throws Exception {
        add();//在第一个学生里面增加性别标签<sex>男</sex>
        //add2();//在第一个学生的<name>张三</name>标签后增加<home>沭阳</home>
        //delete();//删除上面增加的性别标签<sex>男</sex>
        //modify();//将上面增加的标签<home>沭阳</home>改为<home>江苏</home>
        //select();//查询所有学生姓名
    }
    //在第一个学生里面增加性别标签<sex>男</sex>
    private static void add() throws Exception {
        Document document = getRoot();
        Element s1=root.element("student");
        Element sex1=s1.addElement("sex");
        sex1.setText("男");
        writeBack(document);
    }
    //在第一个学生的<name>张三</name>标签后增加<home>沭阳</home>
    private static void add2() throws Exception {
        Document document = getRoot();
        Element s1=root.element("student");
        List<Element>list=s1.elements();
        Element home=DocumentHelper.createElement("home");
        home.setText("沭阳");
        list.add(1,home );
        writeBack(document);
    }
    //删除上面增加的性别标签<sex>男</sex>
    private static void delete() throws Exception{
        Document document = getRoot();
        Element s1=root.element("student");
        s1.remove(s1.element("sex"));
        writeBack(document);
    }
    //将上面增加的标签<home>沭阳</home>改为<home>江苏</home>
    private static void modify() throws Exception{
        Document document = getRoot();
        Element s1=root.element("student");
        s1.element("home").setText("江苏");
        writeBack(document);
    }
    //查询所有学生姓名
    private static void select() throws Exception{
        Document document = getRoot();
        List<Element> list=root.elements("student");
        for(int i=0;i<list.size();i++)
        {
            System.out.println(list.get(i).elementText("name"));
        }
    }
    //XML回写
    private static void writeBack(Document document)throws Exception {
        OutputFormat format=OutputFormat.createPrettyPrint();
        XMLWriter writer=new XMLWriter(new FileOutputStream("src/1.xml"), format);
        writer.write(document);
        writer.close();
    }
    //初始化
    private static Document getRoot() throws DocumentException {
        SAXReader saxReader=new SAXReader();
        Document document=saxReader.read("src/1.xml");
        root=document.getRootElement();
        return document;
    }
}
复制代码
posted @ 2017-09-26 10:24  小学生II  阅读(344)  评论(0编辑  收藏  举报