20.
21. Element root = doc.getRootElement();
22.
23. System.out.println("root element: " + root.getName());
24.
25. List childList = root.elements();
26.
27. System.out.println(childList.size());
28.
29. List childList2 = root.elements("hello");
30.
31. System.out.println(childList2.size());
32.
33. Element first = root.element("hello");
34.
35. System.out.println(first.attributeva lue("age"));
36.
37. for(Iterator iter = root.elementIterator(); iter.hasNext();)
38. {
39. Element e = (Element)iter.next();
40.
41. System.out.println(e.attributeva lue("age"));
42. }
43.
44. System.out.println("---------------------------");
45.
46. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
47. DocumentBuilder db = dbf.newDocumentBuilder();
48. org.w3c.dom.Document document = db.parse(new File("student2.xml"));
49.
50. DOMReader domReader = new DOMReader();
51.
52. //将JAXP的Document转换为dom4j的Document
53. Document d = domReader.read(document);
54.
55. Element rootElement = d.getRootElement();
56.
57. System.out.println(rootElement.getName());
58.
59. }
60. }
Java代码
1. import java.io.FileWriter;
2.
3. import org.jdom.Attribute;
4. import org.jdom.Document;
5. import org.jdom.Element;
6. import org.jdom.output.Format;
7. import org.jdom.output.XMLOutputter;
8.
9. public class Test3
10. {
11. public static void main(String[] args) throws Exception
12. {
13. Document document = new Document();
14.
15. Element root = new Element("联系人列表").setAttribute(new Attribute("公司",
16. "A集团"));
17.
18. document.addContent(root);
19.
20. Element contactPerson = new Element("联系人");
21.
22. root.addContent(contactPerson);
23.
24. contactPerson
25. .addContent(new Element("姓名").setText("张三"))
26. .addContent(new Element("公司").setText("A公司"))
27. .addContent(new Element("电话").setText("021-55556666"))
28. .addContent(
29. new Element("地址")
30. .addContent(new Element("街道").setText("5街"))
31. .addContent(new Element("城市").setText("上海"))
32. .addContent(new Element("省份").setText("上海市")));
33.
34. XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
35. .setIndent(" ").setEncoding("gbk"));
36.
37. output.output(document, new FileWriter("contact.xml"));
38.
39. }
40. }