dom4j中对xml的查增

时间:2023-11-25 16:30:02

package dom;

import java.io.FileWriter;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4jDemo {
@Test
public void readDemo() throws Exception{
SAXReader read=new SAXReader();
Document dom=read.read("./xml/user.xml");

//获得根元素;
Element en= dom.getRootElement();
//获取里面中的子元素
Iterator<Element> it=en.elementIterator();
while(it.hasNext()){
Element eUser=it.next();
String id=eUser.attributeValue("id");//这里还可以分开得到,下面的name和age也是一样

// String id1=eUser.attribute("id").getValue();

String name=eUser.elementText("name");
String age=eUser.elementText("age");
System.out.println("id="+id+" name="+name+" age="+age);

}

}
//这里是创建一个新节点
@Test
public void creatDemo() throws Exception{
SAXReader read=new SAXReader();
Document dom=read.read("./xml/user.xml");

Element en=dom.getRootElement();

Element eUser=en.addElement("user");
eUser.addAttribute("id" , "b001");
eUser.addElement("name").addText("xiaoming");
//这里有一个小细节,这里的setText最终还是调用addText所以他们的效果是一样的
eUser.addElement("age").setText("32");

//把贴加的元素放入到文件中存储起来
XMLWriter we=new XMLWriter(new FileWriter("./xml/user.xml"));
we.write(dom);
we.close();

}
}

--------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="A001">
<name>Jack</name>
<age>23</age>
</user>
<user id="A002">
<name>张三</name>
<age>22</age>
</user>
<user id="A003">
<name>Mike</name>
<age>32</age>
</user>
<user id="B001">
<name>李四</name>
<age>25</age>
</user>
<user id="b001">
<name>xiaoming</name>
<age>32</age>
</user>
</users>