首先我们给出一段示例程序:
import
java.io.File;
import
java.io.FileWriter;
import
java.util.Iterator;
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
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;
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
public
class
DOM4JTest
{
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/***//***/
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/***//***/
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/***//***/
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/***//**
*DOM4J读写XML示例
*
*@paramargs
*@throwsException
*/
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
publicstaticvoidmain(String[]args)
{
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
XMLWriterwriter=null;//声明写XML的对象
SAXReaderreader=newSAXReader();
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
OutputFormatformat=OutputFormat.createPrettyPrint();
format.setEncoding("GBK");//设置XML文件的编码格式
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
StringfilePath="d:\\student.xml";
Filefile=newFile(filePath);
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(file.exists())
{
Documentdocument=reader.read(file);//读取XML文件
Elementroot=document.getRootElement();//得到根节点
booleanbl=false;
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(Iteratori=root.elementIterator("学生");i.hasNext();)
{
Elementstudent=(Element)i.next();
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(student.attributeValue("sid").equals("001"))
{
//修改学生sid=001的学生信息
student.selectSingleNode("姓名").setText("王五");
student.selectSingleNode("年龄").setText("25");
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
writer=newXMLWriter(newFileWriter(filePath),format);
writer.write(document);
writer.close();
bl=true;
break;
}
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(bl)
{
//添加一个学生信息
Elementstudent=root.addElement("学生");
student.addAttribute("sid","100");
Elementsid=student.addElement("编号");
sid.setText("100");
Elementname=student.addElement("姓名");
name.setText("嘎嘎");
Elementsex=student.addElement("性别");
sex.setText("男");
Elementage=student.addElement("年龄");
age.setText("21");
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
writer=newXMLWriter(newFileWriter(filePath),format);
writer.write(document);
writer.close();
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
}else
{
//新建student.xml文件并新增内容
Document_document=DocumentHelper.createDocument();
Element_root=_document.addElement("学生信息");
Element_student=_root.addElement("学生");
_student.addAttribute("sid","001");
Element_id=_student.addElement("编号");
_id.setText("001");
Element_name=_student.addElement("姓名");
_name.setText("灰机");
Element_age=_student.addElement("年龄");
_age.setText("18");
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
writer=newXMLWriter(newFileWriter(file),format);
writer.write(_document);
writer.close();
}
System.out.println("操作结束!");
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
}catch(Exceptione)
{
e.printStackTrace();
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/InBlock.gif)
}
}
执行结果应该是这样:
![](http://writeblog.csdn.net/images/blogjava_net/biiau/2234.jpg)
循环解析节点:
private
void
getAllNodes(Stringxml)
{
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
Documentauthtmp=DocumentHelper.parseText(xml);
List<Element>list=authtmp.selectNodes("//sms/node");
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(intj=0;j<list.size();j++)
{
Elementnode=(Element)list.get(j);
nodeByNodes(node);
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
}catch(Exceptione)
{
e.printStackTrace();
}
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
private
void
nodeByNodes(Elementnode)
{
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(node.element("node")!=null)
{
Stringid=node.attributeValue("id");
Stringname=node.attributeValue("name");
System.out.print(id+"-------");
System.out.println(name);
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(Iteratori=node.elementIterator("node");i.hasNext();)
{
ElementnewNode=(Element)i.next();
nodeByNodes(newNode);
}
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
}else
{
Stringid=node.attributeValue("id");
Stringname=node.attributeValue("name");
System.out.print(id+"-------");
System.out.println(name);
}
}
其次DOM4J的解释
一.Document对象相关
1.读取XML文件,获得document对象.
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
SAXReaderreader=
newSAXReader();
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
Documentdocument
=
reader.read(
new
File(
"
input.xml
"
));
2.解析XML形式的文本,得到document对象.
Stringtext
=
"
<members></members>
";
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
Documentdocument
=
DocumentHelper.parseText(text);
3.主动创建document对象.
Documentdocument
=DocumentHelper.createDocument();
![](http://writeblog.csdn.net/Images/OutliningIndicators/None.gif)
Elementroot
=
document.addElement(
"
members
"
);
//
创建根节点
二.节点相关
1.获取文档的根节点.
ElementrootElm
=
document.getRootElement();
2.取得某节点的单个子节点.
ElementmemberElm
=
root.element(
"
member
"
);
//
"member"是节点名
3.取得节点的文字
String text
=
memberElm.getText();
也可以用:
String text
=
root.elementText(
"
name
"
);
这个是取得根节点下的name字节点的文字.
4.取得某节点下名为"member"的所有字节点并进行遍历.
5.对某节点下的所有子节点进行遍历.
for
(Iteratorit
=
root.elementIterator();it.hasNext();)
{
Elementelement=(Element)it.next();
//dosomething
}
6.在某节点下添加子节点.
Element ageElm
=
newMemberElm.addElement(
"
age
"
);
7.设置节点文字.
ageElm.setText(
"
29
"
);
8.删除某节点.
parentElm.remove(childElm);
//
childElm是待删除的节点,parentElm是其父节点
9.添加一个CDATA节点.
Element contentElm
=
infoElm.addElement(
"
content
"
);
contentElm.addCDATA(diary.getContent());
contentElm.getText(); // 特别说明:获取节点的CDATA值与获取节点的值是一个方法
contentElm.clearContent(); //清除节点中的内容,CDATA亦可
三.属性相关.
1.取得某节点下的某属性
Element root
=
document.getRootElement();
Attribute attribute
=
root.attribute(
"
size
"
);
//
属性名name
2.取得属性的文字
String text
=
attribute.getText();
也可以用:
String text2
=
root.element(
"
name
"
).attributeValue(
"
firstname
"
);
这个是取得根节点下name字节点的属性firstname的值.
3.遍历某节点的所有属性
Elementroot
=
document.getRootElement();
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
for
(Iteratorit
=
root.attributeIterator();it.hasNext();)
{
Attributeattribute=(Attribute)it.next();
Stringtext=attribute.getText();
System.out.println(text);
}
4.设置某节点的属性和文字.
newMemberElm.addAttribute(
"
name
"
,
"
sitinspring
"
);
5.设置属性的文字
Attribute attribute
=
root.attribute(
"
name
"
);
attribute.setText(
"
sitinspring
"
);
6.删除某属性
Attribute attribute
=
root.attribute(
"
size
"
);
//
属性名name
root.remove(attribute);
四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.
XMLWriter writer
=
new
XMLWriter(
new
FileWriter(
"
output.xml
"
));
writer.write(document);
writer.close();
2.文档中含有中文,设置编码格式写入的形式.
OutputFormat format
=
OutputFormat.createPrettyPrint();
format.setEncoding(
"
GBK
"
);
//
指定XML编码
XMLWriter writer
=
new
XMLWriter(
new
FileWriter(
"
output.xml
"
),format);
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
writer.write(document);
writer.close();
五.字符串与XML的转换
1.将字符串转化为XML
String text
=
"
<members> <member>sitinspring</member> </members>
"
;
Document document
=
DocumentHelper.parseText(text);
2.将文档或节点的XML转化为字符串.
SAXReader reader
=
new
SAXReader();
Document document
=
reader.read(
new
File(
"
input.xml
"
));
Element root
=
document.getRootElement();
String docXmlText
=
document.asXML();
String rootXmlText
=
root.asXML();
Element memberElm
=
root.element(
"
member
"
);
String memberXmlText
=
memberElm.asXML();
出自 http://www.blogjava.net/biiau/archive/2008/09/24/231005.html