首先我们给出一段示例程序:
None.gifimport java.io.File;
None.gif
import java.io.FileWriter;
None.gif
import java.util.Iterator;
None.gif
None.gif
import org.dom4j.Document;
None.gif
import org.dom4j.DocumentHelper;
None.gif
import org.dom4j.Element;
None.gif
import org.dom4j.io.OutputFormat;
None.gif
import org.dom4j.io.SAXReader;
None.gif
import org.dom4j.io.XMLWriter;
None.gif
ExpandedBlockStart.gif
publicclass DOM4JTest {
InBlock.gif
ExpandedSubBlockStart.gif
/***/
ExpandedSubBlockStart.gif
/***/
ExpandedSubBlockStart.gif
/***/
ExpandedSubBlockStart.gif
/**
InBlock.gif     * DOM4J读写XML示例
InBlock.gif     *
InBlock.gif     *
@param args
InBlock.gif     *
@throws Exception
ExpandedSubBlockEnd.gif
*/
ExpandedSubBlockStart.gif
publicstaticvoid main(String[] args) {
ExpandedSubBlockStart.gif
try{
InBlock.gif            XMLWriter writer
=null;// 声明写XML的对象
InBlock.gif
           SAXReader reader =new SAXReader();
InBlock.gif
InBlock.gif            OutputFormat format
= OutputFormat.createPrettyPrint();
InBlock.gif            format.setEncoding(
"GBK");// 设置XML文件的编码格式
InBlock.gif
InBlock.gif            String filePath
="d:\\student.xml";
InBlock.gif            File file
=new File(filePath);
ExpandedSubBlockStart.gif
if (file.exists()) {
InBlock.gif                Document document
= reader.read(file);// 读取XML文件
InBlock.gif
               Element root = document.getRootElement();// 得到根节点
InBlock.gif
boolean bl =false;
ExpandedSubBlockStart.gif
for (Iterator i = root.elementIterator("学生"); i.hasNext();) {
InBlock.gif                    Element student
= (Element) i.next();
ExpandedSubBlockStart.gif
if (student.attributeValue("sid").equals("001")) {
InBlock.gif
// 修改学生sid=001的学生信息
InBlock.gif
                       student.selectSingleNode("姓名").setText("王五");
InBlock.gif                        student.selectSingleNode(
"年龄").setText("25");
InBlock.gif
InBlock.gif                        writer
=new XMLWriter(new FileWriter(filePath), format);
InBlock.gif                        writer.write(document);
InBlock.gif                        writer.close();
InBlock.gif                        bl
=true;
InBlock.gif
break;
ExpandedSubBlockEnd.gif                    }
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockStart.gif
if (bl) {
InBlock.gif
// 添加一个学生信息
InBlock.gif
                   Element student = root.addElement("学生");
InBlock.gif                    student.addAttribute(
"sid", "100");
InBlock.gif                    Element sid
= student.addElement("编号");
InBlock.gif                    sid.setText(
"100");
InBlock.gif                    Element name
= student.addElement("姓名");
InBlock.gif                    name.setText(
"嘎嘎");
InBlock.gif                    Element sex
= student.addElement("性别");
InBlock.gif                    sex.setText(
"");
InBlock.gif                    Element age
= student.addElement("年龄");
InBlock.gif                    age.setText(
"21");
InBlock.gif
InBlock.gif                    writer
=new XMLWriter(new FileWriter(filePath), format);
InBlock.gif                    writer.write(document);
InBlock.gif                    writer.close();
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockStart.gif            }
else{
InBlock.gif
// 新建student.xml文件并新增内容
InBlock.gif
               Document _document = DocumentHelper.createDocument();
InBlock.gif                Element _root
= _document.addElement("学生信息");
InBlock.gif                Element _student
= _root.addElement("学生");
InBlock.gif                _student.addAttribute(
"sid", "001");
InBlock.gif                Element _id
= _student.addElement("编号");
InBlock.gif                _id.setText(
"001");
InBlock.gif                Element _name
= _student.addElement("姓名");
InBlock.gif                _name.setText(
"灰机");
InBlock.gif                Element _age
= _student.addElement("年龄");
InBlock.gif                _age.setText(
"18");
InBlock.gif
InBlock.gif                writer
=new XMLWriter(new FileWriter(file), format);
InBlock.gif                writer.write(_document);
InBlock.gif                writer.close();
ExpandedSubBlockEnd.gif            }
InBlock.gif            System.out.println(
"操作结束! ");
ExpandedSubBlockStart.gif        }
catch (Exception e) {
InBlock.gif            e.printStackTrace();
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockEnd.gif    }
ExpandedBlockEnd.gif}
执行结果应该是这样:
2234.jpg
循环解析节点:
ExpandedBlockStart.gifprivatevoid getAllNodes(String xml) {
ExpandedSubBlockStart.gif
try{
InBlock.gif            Document authtmp
= DocumentHelper.parseText(xml);
InBlock.gif            List
<Element> list = authtmp.selectNodes("//sms/node");
ExpandedSubBlockStart.gif
for (int j =0; j < list.size(); j++) {
InBlock.gif                Element node
= (Element) list.get(j);
InBlock.gif                nodeByNodes(node);
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockStart.gif        }
catch (Exception e) {
InBlock.gif            e.printStackTrace();
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
None.gif
ExpandedBlockStart.gif
privatevoid nodeByNodes(Element node) {
ExpandedSubBlockStart.gif
if (node.element("node") !=null) {
InBlock.gif            String id
= node.attributeValue("id");
InBlock.gif            String name
= node.attributeValue("name");
InBlock.gif            System.out.print(id
+"-------");
InBlock.gif            System.out.println(name);
ExpandedSubBlockStart.gif
for (Iterator i = node.elementIterator("node"); i.hasNext();) {
InBlock.gif                Element newNode
= (Element) i.next();
InBlock.gif                nodeByNodes(newNode);
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockStart.gif        }
else{
InBlock.gif            String id
= node.attributeValue("id");
InBlock.gif            String name
= node.attributeValue("name");
InBlock.gif            System.out.print(id
+"-------");
InBlock.gif            System.out.println(name);
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
其次DOM4J的解释
一.Document对象相关

1.读取XML文件,获得document对象.
None.gif      SAXReader reader =
new SAXReader();
None.gif      Document   document
=
reader.read(
new
File(
"
input.xml
"
));

2.解析XML形式的文本,得到document对象.

None.gif
String text
=
"
<members></members>";
None.gif      Document document
=
DocumentHelper.parseText(text);

3.主动创建document对象.
None.gif
     Document document = DocumentHelper.createDocument();
None.gif      Element root
=
document.addElement(
"
members
"
);
//
创建根节点

二.节点相关

1.获取文档的根节点.
None.gif
Element rootElm
=
document.getRootElement();

2.取得某节点的单个子节点.

None.gif
Element memberElm
=
root.element(
"
member
"
);
//
"member"是节点名

3.取得节点的文字

None.gif
String text
=
memberElm.getText();
也可以用:

None.gif
String text
=
root.elementText(
"
name
"
);
这个是取得根节点下的name字节点的文字.


4.取得某节点下名为"member"的所有字节点并进行遍历.

None.gif
List nodes
=
rootElm.elements(
"
member");
None.gif
ExpandedBlockStart.gif
for
(Iterator it
=
nodes.iterator(); it.hasNext();)
{
InBlock.gif    Element elm
= (Element) it.next();
InBlock.gif
// do something
ExpandedBlockEnd.gif
}

5.对某节点下的所有子节点进行遍历.

ExpandedBlockStart.gif
for
(Iterator it
=
root.elementIterator();it.hasNext();)
{
InBlock.gif                 Element element
= (Element) it.next();
InBlock.gif
// do something
ExpandedBlockEnd.gif
            }

6.在某节点下添加子节点.

None.gif
Element ageElm
=
newMemberElm.addElement(
"
age
"
);

7.设置节点文字.

None.gif
ageElm.setText(
"
29
"
);

8.删除某节点.

None.gif
parentElm.remove(childElm);
//
childElm是待删除的节点,parentElm是其父节点

9.添加一个CDATA节点.
None.gif
        Element contentElm
=
infoElm.addElement(
"
content
"
);
None.gif         contentElm.addCDATA(diary.getContent());
           contentElm.getText(); // 特别说明:获取节点的CDATA值与获取节点的值是一个方法
           contentElm.clearContent(); //清除节点中的内容,CDATA亦可


三.属性相关.

1.取得某节点下的某属性

None.gif
            Element root
=
document.getRootElement();    
None.gif             Attribute attribute
=
root.attribute(
"
size
"
);
//
属性名name

2.取得属性的文字

None.gif
            String text
=
attribute.getText();
也可以用:

None.gif
String text2
=
root.element(
"
name
"
).attributeValue(
"
firstname
"
);
这个是取得根节点下name字节点的属性firstname的值.


3.遍历某节点的所有属性

None.gif
 Element root
=
document.getRootElement();    
ExpandedBlockStart.gif
for
(Iterator it
=
root.attributeIterator();it.hasNext();)
{
InBlock.gif                 Attribute attribute
= (Attribute) it.next();
InBlock.gif                 String text
=attribute.getText();
InBlock.gif                 System.out.println(text);
ExpandedBlockEnd.gif             }

4.设置某节点的属性和文字.

None.gif
newMemberElm.addAttribute(
"
name
"
,
"
sitinspring
"
);

5.设置属性的文字

None.gif
            Attribute attribute
=
root.attribute(
"
name
"
);
None.gif             attribute.setText(
"
sitinspring
"
);

6.删除某属性
None.gif
            Attribute attribute
=
root.attribute(
"
size
"
);
//
属性名name
None.gif
            root.remove(attribute);

四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.

None.gif
XMLWriter writer
=
new
XMLWriter(
new
FileWriter(
"
output.xml
"
));
None.gifwriter.write(document);
None.gifwriter.close();

2.文档中含有中文,设置编码格式写入的形式.
None.gif
            OutputFormat format
=
OutputFormat.createPrettyPrint();
None.gif             format.setEncoding(
"
GBK
"
);    
//
指定XML编码        
None.gif
            XMLWriter writer
=
new
XMLWriter(
new
FileWriter(
"
output.xml
"
),format);
None.gif
None.gif             writer.write(document);
None.gif             writer.close();

五.字符串与XML的转换

1.将字符串转化为XML

None.gif
String text
=
"
<members> <member>sitinspring</member> </members>
"
;
None.gifDocument document
=
DocumentHelper.parseText(text);

2.将文档或节点的XML转化为字符串.

None.gif
            SAXReader reader
=
new
SAXReader();
None.gif             Document   document
=
reader.read(
new
File(
"
input.xml
"
));            
None.gif             Element root
=
document.getRootElement();                
None.gif             String docXmlText
=
document.asXML();
None.gif             String rootXmlText
=
root.asXML();
None.gif             Element memberElm
=
root.element(
"
member
"
);
None.gif             String memberXmlText
=
memberElm.asXML();