转载自:http://xhy0422.iteye.com/blog/50235
版权声明:
本文由冰云完成,首发于CSDN,未经许可,不得使用于任何商业用途。
文中代码部分引用自DOM4J文档。
欢迎转载,但请保持文章及版权声明完整。
如需联络请发邮件:icecloud(AT)sina.com
|
Attribute | Attribute定义了XML的属性 |
Branch | Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为, |
CDATA | CDATA 定义了XML CDATA 区域 |
CharacterData | CharacterData是一个标识借口,标识基于字符的节点。如CDATA,Comment, Text. |
Comment | Comment 定义了XML注释的行为 |
Document | 定义了XML文档 |
DocumentType | DocumentType 定义XML DOCTYPE声明 |
Element | Element定义XML 元素 |
ElementHandler | ElementHandler定义了 Element 对象的处理器 |
ElementPath | 被ElementHandler使用,用于取得当前正在处理的路径层次信息 |
Entity | Entity定义 XML entity |
Node | Node为所有的dom4j中XML节点定义了多态行为 |
NodeFilter | NodeFilter 定义了在dom4j节点中产生的一个滤镜或谓词的行为(predicate) |
ProcessingInstruction | ProcessingInstruction 定义 XML 处理指令. |
Text | Text 定义XML 文本节点. |
Visitor | Visitor 用于实现Visitor模式. |
XPath | XPath 在分析一个字符串后会提供一个XPath 表达式 |
// 从文件读取XML,输入文件名,返回XML文档
publicDocument read(String fileName)
throwsMalformedURLException, DocumentException {
SAXReader reader =
newSAXReader();
Document document = reader.read(
newFile(fileName));
returndocument;
}
|
publicElement getRootElement(Document doc){
returndoc.getRootElement();
}
|
// 枚举所有子节点
for( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
}
// 枚举名称为foo的节点
for( Iterator i = root.elementIterator(foo); i.hasNext();) {
Element foo = (Element) i.next();
// do something
}
// 枚举属性
for( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
|
publicvoidtreeWalk() {
treeWalk(getRootElement());
}
publicvoidtreeWalk(Element element) {
for(
inti = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if(node
instanceofElement) {
treeWalk((Element) node);
}
else{ // do something....
}
}
}
|
publicclassMyVisitor
extendsVisitorSupport {
publicvoidvisit(Element element){
System.out.println(element.getName());
}
publicvoidvisit(Attribute attr){
System.out.println(attr.getName());
}
}
调用: root.accept(new MyVisitor())
|
publicvoidbar(Document document) {
List list = document.selectNodes( //foo/bar );
Node node = document.selectSingleNode(//foo/bar/author);
String name = node.valueOf( @name );
}
|
publicvoidfindLinks(Document document)
throwsDocumentException {
List list = document.selectNodes( //a/@href );
for(Iterator iter = list.iterator(); iter.hasNext(); ) {
Attribute attribute = (Attribute) iter.next();
String url = attribute.getValue();
}
}
|
// XML转字符串
Document document = ...;
String text = document.asXML();
// 字符串转XML
String text = <person> <name>James</name> </person>;
Document document = DocumentHelper.parseText(text);
|
publicDocument styleDocument(
Document document,
String stylesheet
)
throwsException {
// load the transformer using JAXP
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
newStreamSource( stylesheet )
);
// now lets style the given document
DocumentSource source =
newDocumentSource( document );
DocumentResult result =
newDocumentResult();
transformer.transform( source, result );
// return the transformed document
Document transformedDoc = result.getDocument();
returntransformedDoc;
}
|
publicDocument 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);
returndocument;
}
|
FileWriter out =
newFileWriter( foo.xml );
document.write(out);
|
publicvoidwrite(Document document)
throwsIOException {
// 指定文件
XMLWriter writer =
newXMLWriter(
newFileWriter( output.xml )
);
writer.write( document );
writer.close();
// 美化格式
OutputFormat format = OutputFormat.createPrettyPrint();
writer =
newXMLWriter( System.out, format );
writer.write( document );
// 缩减格式
format = OutputFormat.createCompactFormat();
writer =
newXMLWriter( System.out, format );
writer.write( document );
}
|
holen.xml |
<?xml version="1.0" encoding="UTF-8"?>
<books>
<!--This is a test for dom4j, holen, 2004.9.11-->
<book show="yes">
<title>Dom4j Tutorials</title>
</book>
<book show="yes">
<title>Lucene Studing</title>
</book>
<book show="no">
<title>Lucene in Action</title>
</book>
<owner>O'Reilly</owner>
</books>
|
/**
* 建立一个XML文档,文档名由输入属性决定
*
@paramfilename 需建立的文件名
*
@return返回操作结果, 0表失败, 1表成功
*/
publicintcreateXMLFile(String filename){
/** 返回操作结果, 0表失败, 1表成功 */
intreturnValue = 0;
/** 建立document对象 */
Document document = DocumentHelper.createDocument();
/** 建立XML文档的根books */
Element booksElement = document.addElement("books");
/** 加入一行注释 */
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
/** 加入第一个book节点 */
Element bookElement = booksElement.addElement("book");
/** 加入show属性内容 */
bookElement.addAttribute("show","yes");
/** 加入title节点 */
Element titleElement = bookElement.addElement("title");
/** 为title设置内容 */
titleElement.setText("Dom4j Tutorials");
/** 类似的完成后两个book */
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","yes");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene Studing");
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","no");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene in Action");
/** 加入owner节点 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try{
/** 将document中的内容写入文件中 */
XMLWriter writer =
newXMLWriter(
newFileWriter(
newFile(filename)));
writer.write(document);
writer.close();
/** 执行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
returnreturnValue;
}
|
<?xml version="1.0" encoding="UTF-8"?>
<books><!--This is a test for dom4j, holen, 2004.9.11--><book show="yes"><title>Dom4j Tutorials</title></book><book show="yes"><title>Lucene Studing</title></book><book show="no"><title>Lucene in Action</title></book><owner>O'Reilly</owner></books>
|
/**
* 修改XML文件中内容,并另存为一个新文件
* 重点掌握dom4j中如何添加节点,修改节点,删除节点
*
@paramfilename 修改对象文件
*
@paramnewfilename 修改后另存为该文件
*
@return返回操作结果, 0表失败, 1表成功
*/
publicintModiXMLFile(String filename,String newfilename){
intreturnValue = 0;
try{
SAXReader saxReader =
newSAXReader();
Document document = saxReader.read(
newFile(filename));
/** 修改内容之一: 如果book节点中show属性的内容为yes,则修改成no */
/** 先用xpath查找对象 */
List list = document.selectNodes("/books/book/@show" );
Iterator iter = list.iterator();
while(iter.hasNext()){
Attribute attribute = (Attribute)iter.next();
if(attribute.getValue().equals("yes")){
attribute.setValue("no");
}
}
/**
* 修改内容之二: 把owner项内容改为Tshinghua
* 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个属性type
*/
list = document.selectNodes("/books/owner" );
iter = list.iterator();
if(iter.hasNext()){
Element ownerElement = (Element)iter.next();
ownerElement.setText("Tshinghua");
Element dateElement = ownerElement.addElement("date");
dateElement.setText("2004-09-11");
dateElement.addAttribute("type","Gregorian calendar");
}
/** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点 */
list = document.selectNodes("/books/book");
iter = list.iterator();
while(iter.hasNext()){
Element bookElement = (Element)iter.next();
Iterator iterator = bookElement.elementIterator("title");
while(iterator.hasNext()){
Element titleElement=(Element)iterator.next();
if(titleElement.getText().equals("Dom4j Tutorials")){
bookElement.remove(titleElement);
}
}
}
try{
/** 将document中的内容写入文件中 */
XMLWriter writer =
newXMLWriter(
newFileWriter(
newFile(newfilename)));
writer.write(document);
writer.close();
/** 执行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
}
catch(Exception ex){
ex.printStackTrace();
}
returnreturnValue;
}
|
/**
* 格式化XML文档,并解决中文问题
*
@paramfilename
*
@return
*/
publicintformatXMLFile(String filename){
intreturnValue = 0;
try{
SAXReader saxReader =
newSAXReader();
Document document = saxReader.read(
newFile(filename));
XMLWriter writer =
null;
/** 格式化输出,类型IE浏览一样 */
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML编码 */
format.setEncoding("GBK");
writer=
newXMLWriter(
newFileWriter(
newFile(filename)),format);
writer.write(document);
writer.close();
/** 执行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex){
ex.printStackTrace();
}
returnreturnValue;
}
|
Dom4jDemo.java |
packagecom.holen.dom4j;
importjava.io.File;
importjava.io.FileWriter;
importjava.util.Iterator;
importjava.util.List;
importorg.dom4j.Attribute;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
/**
*
@authorHolen Chen</
|