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

dom4j解析xml文件

时间:2015-05-13 06:05:06      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
<!DOCTYPE bookshelf SYSTEM "book.dtd">
-->
<bookshelf>
    <book>
        <name bookname="thinkinjava">Think in Java</name>
        <author>Bruce Eckel</author>
        <price>95.00</price>
    </book>
    <book>
        <name>Effective Java</name>
        <author>Joshua Bloch</author>
        <price>52.00</price>
    </book>
</bookshelf>
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.Iterator;
import java.util.List;

public class Dom4jDemo {

    public static void main(String[] args) throws Exception {

        // parse
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("day02/src/book.xml"));

        // iterate through child elements of root
        Element root = document.getRootElement();
        for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
            Element element = (Element) iterator.next();
            System.out.println(element.getName());
        }

        // get attribute of 1st book, name tag
        Element book1 = (Element) root.elements("book").get(0);
        System.out.println(book1.element("name").attributeValue("bookname"));

        // get name of 2rd book
        Element book2 = (Element) root.elements("book").get(1);
        System.out.println(book2.element("name").getText());

        // add book1
        book1.addElement("version").setText("1.0");

        // add book2
        List list = book2.elements(); // name, author[, version], price
        Element version = DocumentHelper.createElement("version");
        version.setText("2.0");
        list.add(2, version);

        // delete price of book1
        Element price1 = book1.element("price");
        price1.getParent().remove(price1);

        // update price of book2
        Element price2 = book2.element("price");
        price2.setText("1111");

        write(document);
    }

    // write to a file
    public static void write(Document document) throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileOutputStream("day02/src/book2.xml"), format);
        writer.write(document);
        writer.close();
    }

}

 

dom4j解析xml文件

标签:

原文地址:http://www.cnblogs.com/geb515/p/4499172.html

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