使用dom4j解析xml文档

注意:在使用dom4j解析xml文档的时候首先我们需要导入dom4j的jar包dom4j-1.6.1.jar

          参考链接:https://www.jianshu.com/p/e8561ea99d03

一.dom4j中,获得Document对象的方式有三种

1.读取xml文件,获得Document对象

2.解析xml形式的文本,得到Document对象,将字符串转换为

3.主动创建Document对象(直接创建)

二、节点对象

1.获取文档的根节点:

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

3.取得节点的文本

4.取得某节点下所有名为“member“的子节点,并进行遍历

5.对某节点下的所有子节点进行遍历(遍历方法2)

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


7.设置节点文本

8.删除某节点

9.添加一个CDATA(前面有说明)节点

Element contentElm =infoElm.addElement("content");contentElm.addCDATA(diary.getContent());

三、节点对象属性

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

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

2.取得属性的文本

String text=attribute.getText();

3.删除某属性

Attribute attribute=root.attribute("size");root.remove(attribute);

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


5.设置某节点的属性和文本

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

6.设置属性的文本

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

四、将文档写入xml文件

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

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

2.文档中含有中文,设置编码格式写入的形式


五、在指定位置插入节点步骤

(1)得到插入位置的节点列表(list)
(2)调用list.add(index,elemnent),由index决定element的插入位置;
(3)Element元素可以通过DocumentHelper对象得到。示例:


六、字符串与xml的转换

1.将字符串转换为xml

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

2.将文档或节点的xml转换为字符串


猜你喜欢

转载自blog.csdn.net/li1325169021/article/details/80729713