博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
dom4j解析和生成XML文件
阅读量:6049 次
发布时间:2019-06-20

本文共 7305 字,大约阅读时间需要 24 分钟。

转化XML

import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;public class Foo {
public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; }}

使用迭代器

document可以通过几个返回Java标准迭代器的方法实现遍历:

public void bar(Document document) throws DocumentException {    Element root = document.getRootElement();    // iterate through child elements of root    for ( Iterator i = root.elementIterator(); i.hasNext(); ) {        Element element = (Element) i.next();        // do something    }    // iterate through child elements of root with element name "foo"    for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {        Element foo = (Element) i.next();        // do something    }    // iterate through attributes of root     for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {        Attribute attribute = (Attribute) i.next();        // do something    } }

快速循环

快速遍历大文件:

public void treeWalk(Document document) {     treeWalk( document.getRootElement() ); } public void treeWalk(Element element) {     for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {         Node node = element.node(i);         if ( node instanceof Element ) {             treeWalk( (Element) node );         }         else {             // do something....         }     } }

创建XML文档

import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class Foo {    public Document createDocument() {        Document document = DocumentHelper.createDocument();        Element root = document.addElement( "root" );        Element author1 = root.addElement( "author" )            .addAttribute( "name", "James" )            .addAttribute( "location", "UK" )            .addText( "James Strachan" );        Element author2 = root.addElement( "author" )            .addAttribute( "name", "Bob" )            .addAttribute( "location", "US" )            .addText( "Bob McWhirter" );        return document;    }}

将文档写入文件

一种快速而且简单的方式如下:

FileWriter out = new FileWriter( "foo.xml" );document.write( out );

如果想要修改输出的格式,如智能缩进输出或者紧凑输出,或者你想要使用writer对象或者OutputStream对象来完成其他任务,则可以使用XMLWriter类。

import org.dom4j.Document;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class Foo {
public void write(Document document) throws IOException { // lets write to a file XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) ); writer.write( document ); writer.close(); // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter( System.out, format ); writer.write( document ); // Compact format to System.out format = OutputFormat.createCompactFormat(); writer = new XMLWriter( System.out, format ); writer.write( document ); }}

与String的转化

如果有到Document或者其他结点如AttributeElement等的引用,则可以用asXML()方法将其转化为默认的XML文本。

Document document = ...;String text = document.asXML();

如果有String形式的XML,则可以使用DocumentHelper.parseText()将其转化为Document

String text = "
James
";Document document = DocumentHelper.parseText(text);

其他操作

1 取得某结点下的某个子节点或属性

Element root = document.getRootElement();Element elem = root.element("book");Attribute attribute = root.attribute("id");

2 取得属性的内容

String text = attribute.getText();

3 删除某属性

Attribute attribute=root.attribute("id"); root.remove(attribute);

一个完整的解析和生成XML文件示例

package test;import java.io.*;import java.util.Iterator;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;import org.dom4j.Attribute;class XMLHelper {    /**     * 解析XML     * @param filename 要解析的XML的文件名     */    public static void resolveXML(String filename) {        try {            SAXReader reader = new SAXReader();            Document document = reader.read(new File(filename));            Element root = document.getRootElement();            System.out.println("Root: " + root.getName());            for (Iterator it = root.elementIterator(); it.hasNext(); ) {                Element e = (Element)it.next();                System.out.print(e.getName());                //遍历属性                for (Iterator it1 = e.attributeIterator(); it1.hasNext(); ) {                    Attribute attribute = (Attribute)it1.next();                    System.out.println("[" + attribute.getName() + ": " +                        attribute.getText() + "]");                }                //遍历子节点                for (Iterator it2 = e.elementIterator(); it2.hasNext(); ) {                    Element ee = (Element)it2.next();                    System.out.println("    " + ee.getName() + ": " +                         ee.getText() + " ");                }            }        } catch (Exception ex) {            ex.printStackTrace();        }    }    public static Document createDocument() {        Document document = DocumentHelper.createDocument();        Element root = document.addElement("bookstore");        //add book        Element book = root.addElement("book")            .addAttribute("category", "COOKING");        book.addElement("title")            .addText("Everyday Italian");        book.addElement("author")            .addText("Giada De Laurentiis");        book.addElement("year")            .addText("2005");        book.addElement("price")            .addText("30.00");        //add book        book = root.addElement("book")            .addAttribute("category", "CHILDREN");        book.addElement("title")            .addText("Harry Potter");        book.addElement("author")            .addText("J K. Rowling");        book.addElement("year")            .addText("2005");        book.addElement("price")            .addText("29.99");        return document;    }    /**     * 生成XML文件     * @param filename 将生成的XML输出到该文件     */    public static void write(String filename) {        Document document = createDocument();         try {            //write to a file            OutputFormat f=OutputFormat.createPrettyPrint();            XMLWriter writer = new XMLWriter(new FileWriter(filename), f);            writer.write(document);            writer.close();            //Pretty print the document to System.out            /*OutputFormat format = OutputFormat.createPrettyPrint();            writer = new XMLWriter(System.out, format);            writer.write(document);*/            //Compact print the document to System.out            /*format = OutputFormat.createCompactFormat();            writer = new XMLWriter(System.out, format);            writer.write(document);*/        } catch (Exception ex) {            ex.printStackTrace();        }    }}public class Main {
public static void main(String[] args) throws Exception{ String filename = "E:\\Eclipse Project\\WebTest\\WebContent\\myxml.xml"; XMLHelper.resolveXML(filename); filename = "E:\\Eclipse Project\\WebTest\\WebContent\\myxml2.xml"; XMLHelper.write(filename); }}

转载:http://blog.csdn.net/foreverling/article/details/50152241

你可能感兴趣的文章
Django组件-cookie与session
查看>>
phpmyadmin导入导出数据库文件最大限制的解决方法
查看>>
404. Sum of Left Leaves
查看>>
IDE vscode识别webpack中alias配置路径
查看>>
向DataTable中添加一行数据的做法
查看>>
你不可不知的T-SQL执行顺序
查看>>
商城管理系统
查看>>
php扩展之xdebug配置
查看>>
mui mui.plusReady() 事件中的变量问题;
查看>>
如何快速提升自己硬实力
查看>>
phonegap入门–2 Android phonegap工程建立
查看>>
我们为什么需要DTO(数据传输对象)
查看>>
Java - 阅读与查找
查看>>
如何在 SQL Server 实例之间传输登录和密码
查看>>
[洛谷1342]请柬
查看>>
[LOJ6277]数列分块入门 1
查看>>
王昆扬老师发来的材料:关于实数的构造
查看>>
Functions Of Several Real Variables_Theorem_3.1.3:Linear approximation
查看>>
python阳历转农历
查看>>
云服务器与传统服务器优缺点分析
查看>>