Dom4j进行XML的解析

一:将dom4j的jar包导入目标工程
二:`public class Dom4jTest {
public static void main(String[] args) throws Exception {

    try {
        run5();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

/**
 *  查询,获取作者的文本内容
 * 
 *  获取第二个节点的作者的文本内容
 * @throws DocumentException 
 */
public static void run1() throws DocumentException{
    //获取解析器对象
    SAXReader reader=new SAXReader();
    //解析,获取document对象
    Document document = reader.read("src/book4.xml");
    //获取根节点
    Element rootElement = document.getRootElement();
    //获取根节点的所有子节点的集合
    List elements = rootElement.elements();
    Element book2 = (Element) elements.get(1);

    Element author = book2.element("作者");

    String text = author.getText();
    System.out.println(text);
}

//添加子节点,注意回写
public static void run2() throws Exception{

    SAXReader reader=new SAXReader();

    Document document = reader.read("src/book4.xml");

    Element root = document.getRootElement();

    List books = root.elements("书");

    Element book2 = (Element) books.get(1);

    book2.addElement("猫").setText("我是猫");//此时还都只是在内存中的操作


    //接下来进行回写的操作
    //创建一个漂亮的格式
    OutputFormat format=OutputFormat.createPrettyPrint();

    org.dom4j.io.XMLWriter writer=new org.dom4j.io.XMLWriter(new FileOutputStream("src/book4.xml"),format);

    writer.write(document);

    writer.close();


}

public static void run3() throws Exception{
    SAXReader reader=new SAXReader();

    Document document = reader.read("src/book4.xml");

    Element rootElement = document.getRootElement();

    Element book2 = (Element) rootElement.elements("书").get(1);


    List elements = book2.elements();

    //创建一个元素对象
    Element dog = DocumentHelper.createElement("狗");
    dog.setText("大狗");

    elements.add(1,dog);

    //回写之前添加漂亮的格式
    OutputFormat format=OutputFormat.createPrettyPrint();


    org.dom4j.io.XMLWriter writer=new org.dom4j.io.XMLWriter(new FileOutputStream("src/book4.xml"),format);
    writer.write(document);
    writer.close();


}

//删除子节点
public static void run5() throws Exception{
    SAXReader reader=new SAXReader();

    Document document = reader.read("src/book4.xml");

    Element rootElement = document.getRootElement();

    //获取猫
    Element book2 = (Element) rootElement.elements("书").get(1);
    Element cat = book2.element("猫");
    //获取父节点
    //cat.getParent();
    book2.remove(cat);
    //回写之前添加漂亮的格式
    OutputFormat format=OutputFormat.createPrettyPrint();


    org.dom4j.io.XMLWriter writer=new org.dom4j.io.XMLWriter(new FileOutputStream("src/book4.xml"),format);
    writer.write(document);
    writer.close();
}

}
`

你可能感兴趣的:(JAVAEE)