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....
}
}
}
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 );
}
}
如果有到Document
或者其他结点如Attribute
、Element
等的引用,则可以用asXML()
方法将其转化为默认的XML文本。
Document document = ...;
String text = document.asXML();
如果有String
形式的XML,则可以使用DocumentHelper.parseText()
将其转化为Document
。
String text = "<person> <name>James</name> </person>";
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);
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);
}
}