dom4j解析示例
收藏信息.xml
<?xml version="1.0" encoding="GB2312" standalone="no"?><PhoneInfo>
<Brand id="0" name="华为">
<Type name="U8650"/>
<Type name="HW123"/>
<Type name="HW321"/>
</Brand>
<Brand id="1" name="苹果">
<Type name="iPhone4"/>
</Brand>
<Brand id="2" name="三星"><type name="s120"/></Brand></PhoneInfo>
解析示例:
1 import java.io.File;
2 import java.io.FileWriter;
3 import java.io.IOException;
4 import java.util.Iterator;
5
6 import org.dom4j.Document;
7 import org.dom4j.DocumentException;
8 import org.dom4j.Element;
9 import org.dom4j.io.OutputFormat;
10 import org.dom4j.io.SAXReader;
11 import org.dom4j.io.XMLWriter;
12
13
14 public class Dom4jParse {
15 public static Document document;
16
17 //获取DOM
18 public static void getDom(){
19 SAXReader saxReader = new SAXReader();
20 try {
21 document = saxReader.read(new File("收藏信息.xml"));
22 } catch (DocumentException e) {
23 e.printStackTrace();
24 }
25
26 }
27
28
29 //获取所有节点信息
30 public static void showInfo(){
31 Element root = document.getRootElement();
32 for(Iterator itBrand=root.elementIterator();itBrand.hasNext();){
33 Element brand = (Element) itBrand.next();
34 System.out.println("品牌"+brand.attributeValue("name"));
35 for(Iterator itType=brand.elementIterator();itType.hasNext();){
36 Element type = (Element) itType.next();
37 System.out.println("\t型号"+type.attributeValue("name"));
38 }
39 }
40
41 }
42
43 //添加节点
44 public static void addNode(){
45 Element root = document.getRootElement();
46 Element eBrand = root.addElement("Brand");
47 eBrand.addAttribute("name", "诺基亚");
48 Element eType = eBrand.addElement("type");
49 eType.addAttribute("name", "直板");
50 saveXml("收藏信息.xml");
51 }
52
53 //更新节点,添加ID属性
54 public static void updateNode(){
55 Element root = document.getRootElement();
56 int id=0;
57 for(Iterator iBrand=root.elementIterator();iBrand.hasNext();){
58 Element brand = (Element)iBrand.next();
59 id++;
60 brand.addAttribute("id", id+"");
61 }
62 saveXml("收藏信息.xml");
63 }
64
65
66 //删除节点
67 public static void deleteNode(){
68 Element root = document.getRootElement();
69 for(Iterator iBrand=root.elementIterator();iBrand.hasNext();){
70 Element brand = (Element)iBrand.next();
71 if(brand.attributeValue("name").equals("诺基亚")){
72 brand.getParent().remove(brand);
73 }
74 }
75 saveXml("收藏信息.xml");
76 }
77
78
79
80
81
82
83 //保存XML
84 public static void saveXml(String path){
85 //输出格式转换器
86 OutputFormat format = OutputFormat.createPrettyPrint();
87 format.setEncoding("GBK2312");
88 XMLWriter writer;
89 try {
90 writer = new XMLWriter(new FileWriter(path), format);
91 writer.write(document);
92 writer.close();
93 } catch (IOException e) {
94 e.printStackTrace();
95 }
96 }
97
98
99 public static void main(String[] args) {
100 Dom4jParse dp = new Dom4jParse();
101 dp.getDom();
102 dp.showInfo();
103
104 }
105
106
107
108
109
110 }