无聊简介:
- Dom4j 是一个简单、灵活的开放源代码的库。Dom4j是由早期开发JDOM的人分离出来而后独立开发的。与JDOM不同的是,dom4j使用接口和抽象基类,虽然Dom4j的API相对要复杂一些,但它提供了比JDOM更好的灵活性。
- Dom4j是一个非常优秀的Java XML API,具有性能优异、功能强大和极易使用的特点。现在很多软件采用的Dom4j,例如Hibernate,包括sun公司自己的JAXM也用了Dom4j。
- 使用Dom4j开发,需下载dom4j相应的jar文件。
导入 dom4j 1.6.1.jar :
变成奶瓶就能用了:
查看 dom4j-1.6.1/docs/index.html 的 Quick start :
Parsing XML
One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.
import java.net.URL; 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; } }
然后可以查看 dom4j 的 API:
org.dom4j.io
Class SAXReader
java.lang.Object
|--- extended byorg.dom4j.io.SAXReader
public class SAXReader
extends Object
Constructor Summary | |
SAXReader() | |
SAXReader(boolean validating) | |
SAXReader(DocumentFactory factory) | |
SAXReader(DocumentFactory factory, boolean validating) | |
SAXReader(String xmlReaderClassName) | |
SAXReader(String xmlReaderClassName, boolean validating) | |
SAXReader(XMLReader xmlReader) | |
SAXReader(XMLReader xmlReader, boolean validating) |
Method Summary | |
Document | read(File file) Reads a Document from the given File |
Document | read(InputSource in) Reads a Document from the given InputSource using SAX |
Document | read(InputStream in) Reads a Document from the given stream using SAX |
Document | read(InputStream in, String systemId) Reads a Document from the given stream using SAX |
Document | read(Reader reader) Reads a Document from the given Reader using SAX |
Document | read(Reader reader, String systemId) Reads a Document from the given Reader using SAX |
Document | read(String systemId) Reads a Document from the given URL or filename using SAX. |
Document | read(URL url) Reads a Document from the given URL using SAX |
org.dom4j
Interface Document
public interface Document
extends Branch
Element | getRootElement() Returns the root Element for this document. |
org.dom4j
Interface Element
public interface Element
extends Branch
Element | element(String name) Returns the first element for the given local name and any namespace. |
List | elements() Returns the elements contained in this element. |
List | elements(QName qName) Returns the elements contained in this element with the given fully qualified name. |
List | elements(String name) Returns the elements contained in this element with the given local name and any namespace. |
String | getStringValue() Returns the XPath string-value of this node. |
String | getText() Returns the text value of this element without recursing through child elements. |
Attribute | attribute(int index) Returns the attribute at the specified indexGets the |
Attribute | attribute(QName qName) DOCUMENT ME! |
Attribute | attribute(String name) Returns the attribute with the given name |
List | attributes() Returns the Attribute instances this element contains as a backed List so that the attributes may be modified directly using theList interface. |
String | attributeValue(QName qName) This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty. |
String | attributeValue(QName qName, String defaultValue) This returns the attribute value for the attribute with the given fully qualified name or the default value if there is no such attribute value. |
String | attributeValue(String name) This returns the attribute value for the attribute with the given name and any namespace or null if there is no such attribute or the empty string if the attribute value is empty. |
String | attributeValue(String name, String defaultValue) This returns the attribute value for the attribute with the given name and any namespace or the default value if there is no such attribute value. |
导入 JUnit :
导入后左侧出现 JUnit 4 / lib:
如何创建节点:
Creating a new XML document
Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.
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;
}
}
org.dom4j
Class DocumentHelper
java.lang.Object
|--- extended byorg.dom4j.DocumentHelper
public final class DocumentHelper
extends Object
Method Summary | |
static Element |
createElement(String name) |
org.dom4j
Interface Node
void | setText(String text) Sets the text data of this node or this method will throw an UnsupportedOperationException if it is read-only. |
org.dom4j
Interface Branch
public interface Branch
extends Node
Method Summary | |
void | add(Comment comment) Adds the given Comment to this branch. |
void | add(Element element) Adds the given Element to this branch. |
void | add(Node node) Adds the given Node or throws IllegalAddException if the given node is not of a valid type. |
如何更新XML文档:
Writing a document to a file
A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.
FileWriter out = new FileWriter( "foo.xml" ); document.write( out );
If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.
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 ); } }
org.dom4j.io
Class XMLWriter
Constructor Summary | |
XMLWriter() | |
XMLWriter(OutputFormat format) | |
XMLWriter(OutputStream out) | |
XMLWriter(OutputStream out, OutputFormat format) | |
XMLWriter(Writer writer) | |
XMLWriter(Writer writer, OutputFormat format) |
Method Summary | |
void |
close() Closes the underlying Writer |
void | write(Attribute attribute) Writes the given Attribute . |
void | write(CDATA cdata) Writes the given CDATA . |
void | write(Comment comment) Writes the given Comment . |
void | write(Document doc) This will print the Document to the current Writer. |
void | write(DocumentType docType) Writes the given DocumentType . |
void | write(Element element) Writes the , including its s, and its value, and all its content (child nodes) to the current Writer. |
void | write(Entity entity) Writes the given Entity . |
void | write(Namespace namespace) Writes the given Namespace . |
void | write(Node node) Writes the given Node . |
void | write(Object object) Writes the given object which should be a String, a Node or a List of Nodes. |
void | write(ProcessingInstruction processingInstruction) Writes the given ProcessingInstruction . |
void | write(String text) Print out a String , Perfoms the necessary entity escaping and whitespace stripping. |
void | write(Text text) Writes the given Text . |
org.dom4j.io
Class OutputFormat
Constructor Summary | |
OutputFormat() Creates an OutputFormat with no additional whitespace (indent or new lines) added. | |
OutputFormat(String indent) Creates an OutputFormat with the given indent added but no new lines added. | |
OutputFormat(String indent, boolean newlines) Creates an OutputFormat with the given indent added with optional newlines between the Elements. | |
OutputFormat(String indent, boolean newlines, String encoding) Creates an OutputFormat with the given indent added with optional newlines between the Elements and the given encoding format. |
Method Summary | |
static OutputFormat | createCompactFormat() A static helper method to create the default compact format. |
static OutputFormat | createPrettyPrint() A static helper method to create the default pretty printing format. |
void | setEncoding(String encoding) DOCUMENT ME! |
book.xml :
<?xml version="1.0" encoding="UTF-8"?>
<书架>
<书 name="yyyyy">
<售价>109元</售价>
<售价>19元</售价>
<售价>19元</售价>
<售价>209元</售价>
<书名>Java就业培训教程</书名>
<作者>张孝祥</作者>
<售价>19元</售价>
<售价>19元</售价>
<售价>19元</售价>
</书>
<书>
<书名>JavaScript网页开发</书名>
<作者>张孝祥</作者>
<售价>28.00元</售价>
</书>
</书架>
使用 dom4j 对 book.xml 基本的增删改查:
package cn.itcast.dom4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
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 org.junit.Test;
public class Demo1 {
//读取XML文档内容:<书名>Java就业培训教程</书名>
@Test
public void read() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element root = document.getRootElement();
String value = root.element("书").element("书名").getText();
System.out.println("第一本书的书名:"+value);
}
//获取属性值:<书 name="yyyyy">
@Test
public void readAttr() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element root = document.getRootElement();
String attrValue = root.element("书").attributeValue("name");
System.out.println(attrValue);
}
//添加节点:添加到第一个售价节点后:<售价>19元</售价>
@Test
public void add() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element price = DocumentHelper.createElement("售价");
price.setText("19元");
/*Element book = document.getRootElement().element("书");
book.add(price);*/
List list = document.getRootElement().element("书").elements();//得到书的所有孩子。
list.add(1, price); //在list中的指定位置插入元素。
OutputFormat format = OutputFormat.createPrettyPrint(); //漂亮格式
//format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format); //这里一般不要用字符流,因为字符流有时默认是GB2312,它的构造方法又不能指定码表.而XML文档一般都是UTF-8编码的,避免出现XML文档乱码。
writer.write(document);
writer.close();
}
//修改:<售价>39元</售价> 改为 <售价>209元</售价>
@Test
public void update() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element price = (Element)document.getRootElement().element("书").elements("售价").get(1);
price.setText("209元");
OutputFormat format = OutputFormat.createPrettyPrint(); //漂亮格式
//format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format); //这里一般不要用字符流,因为字符流有时默认是GB2312,它的构造方法又不能指定码表.而XML文档一般都是UTF-8编码的,避免出现XML文档乱码。
writer.write(document);
writer.close();
}
//删除:<售价>19元</售价>
@Test
public void delete() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element price = (Element)document.getRootElement().element("书").elements("售价").get(2);
price.getParent().remove(price);
OutputFormat format = OutputFormat.createPrettyPrint(); //漂亮格式
//format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format); //这里一般不要用字符流,因为字符流有时默认是GB2312,它的构造方法又不能指定码表.而XML文档一般都是UTF-8编码的,避免出现XML文档乱码。
writer.write(document);
writer.close();
}
}