java dom4j elementIterator
student.xml
<students>
<student id="1">
<name>张三</name>
<gender>男</gender>
<grade>计算机一班</grade>
<address>广州</address>
</student>
<student id="2">
<name>王甜甜</name>
<gender>男</gender>
<grade>计算机一班</grade>
<address>广州</address>
</student>
</students>
Document doc= DocumentHelper.createDocument();
Element root =doc.addElement("students");
Element student1= root.addElement("student").addAttribute("id", "1");
student1.addElement("name").setText("张三");
student1.addElement("gender").setText("男");
student1.addElement("grade").setText("计算机一班");
student1.addElement("address").setText("广州");
Element studentElem2 = root.addElement("Student");
//2.2 增加属性
studentElem2.addAttribute("id", "2");
//2.3 增加标签,同时设置文本
studentElem2.addElement("name").setText("李四");
studentElem2.addElement("gender").setText("女");
studentElem2.addElement("grade").setText("计算机2班");
studentElem2.addElement("address").setText("广州越秀");
FileOutputStream out= new FileOutputStream("e:/student.xml");
OutputFormat format= OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer= new XMLWriter(out, format);
writer.write(doc);
writer.close();
1 //1.查询到id为2的学生并修改 该名学生!
2 Document doc = new SAXReader().read(new File("e:/student.xml"));
3 Element root = doc.getRootElement();
4 Iterator<Element> it = root.elementIterator();
5
6 while(it.hasNext()) {
7 Element e = it.next();
8 if(e.attributeValue("id").equals("2")){
9
10 e.element("name").setText("王甜甜");
11 break;
12 }
13 }
14
15 //3.1 输出位置
16 FileOutputStream out = new FileOutputStream("e:/student.xml");
17 //3.2 指定格式
18 OutputFormat format = OutputFormat.createPrettyPrint();
19 // 设置编码
20 format.setEncoding("utf-8");
21 XMLWriter writer = new XMLWriter(out,format);
22 //3.3 写出内容
23 writer.write(doc);
24 //3.4关闭资源
25 writer.close();
26 }
1 Document doc = new SAXReader().read(new File("e:/student.xml"));
2 Element root = doc.getRootElement();
3 Iterator<Element> it = root.elementIterator("student");
4
5 while(it.hasNext()) {
6 Element e = it.next();
7 if(e.attributeValue("id").equals("2")){
8
9 e.element("name").setText("王ba");
10 break;
11 }
12 }