1. import java.util.*;
2. import org.dom4j.*;
3.
4. public class testxml {
5.
6. public static void main(String[] args) {
7. String xml =
8. " <file> " +
9. " <chapter id=\"1\" name=\"a\"/> " +
10. " <chapter id=\"2\" name=\"b\"/> " +
11. " <chapter id=\"3\" name=\"c\"/> " +
12. " <chapter id=\"4\" name=\"d\"/> " +
13. " </file> " ;
14. try {
15. //生产doc文档
16. Document doc = DocumentHelper.parseText(xml);
17. //得到根节点
18. Element root = doc.getRootElement();
19. //得到根节点下的chapter节点
20. List elements = root.elements("chapter");
21. //遍历chapter节点
22. Iterator iterator = elements.iterator();
23. while(iterator.hasNext()){
24. Element e = (Element)iterator.next();
25. String id = e.attributeValue("id");
26. //如果id==1 则添加新的节点
27. if("1".equals(id) || "1" == id){
28. //新添加的节点
29. Element enew = e.addElement("chapterNew");
30. //添加属性和值
31. enew.addAttribute("id", "1.1");
32. enew.addAttribute("name", "a.1");
33. }
34. }
35. //打印
36. System.out.println(doc.asXML());
37. } catch (DocumentException e) {
38. e.printStackTrace();
39. }
40. }
41. }
2. import org.dom4j.*;
3.
4. public class testxml {
5.
6. public static void main(String[] args) {
7. String xml =
8. " <file> " +
9. " <chapter id=\"1\" name=\"a\"/> " +
10. " <chapter id=\"2\" name=\"b\"/> " +
11. " <chapter id=\"3\" name=\"c\"/> " +
12. " <chapter id=\"4\" name=\"d\"/> " +
13. " </file> " ;
14. try {
15. //生产doc文档
16. Document doc = DocumentHelper.parseText(xml);
17. //得到根节点
18. Element root = doc.getRootElement();
19. //得到根节点下的chapter节点
20. List elements = root.elements("chapter");
21. //遍历chapter节点
22. Iterator iterator = elements.iterator();
23. while(iterator.hasNext()){
24. Element e = (Element)iterator.next();
25. String id = e.attributeValue("id");
26. //如果id==1 则添加新的节点
27. if("1".equals(id) || "1" == id){
28. //新添加的节点
29. Element enew = e.addElement("chapterNew");
30. //添加属性和值
31. enew.addAttribute("id", "1.1");
32. enew.addAttribute("name", "a.1");
33. }
34. }
35. //打印
36. System.out.println(doc.asXML());
37. } catch (DocumentException e) {
38. e.printStackTrace();
39. }
40. }
41. }