收藏信息.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 //獲取所有節(jié)點(diǎn)信息
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型號(hào)"+type.attributeValue("name"));
38 }
39 }
40
41 }
42
43 //添加節(jié)點(diǎn)
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 //更新節(jié)點(diǎn)懂版,添加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 //刪除節(jié)點(diǎn)
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 //輸出格式轉(zhuǎn)換器
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 }
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者