1
這是一個用JAVA W3C DOM 進行XML操作的例子,包含了查詢、增加、修改、刪除、保存的基本操作。較完整的描述了一個XML的整個操作流程。適合剛?cè)腴TJAVA XML操作的朋友參考和學(xué)習(xí)。
2
3
假設(shè)有XML文件:test1.xml
4
5
<? xml version="1.0" encoding="UTF-8" ?>
6
< books >
7
< book >
8
< name > 哈里波特 </ name >
9
< price > 10 </ price >
10
< memo > 這是一本很好看的書。 </ memo >
11
</ book >
12
< book id ="B02" >
13
< name > 三國演義 </ name >
14
< price > 10 </ price >
15
< memo > 四大名著之一。 </ memo >
16
</ book >
17
< book id ="B03" >
18
< name > 水滸 </ name >
19
< price > 6 </ price >
20
< memo > 四大名著之一。 </ memo >
21
</ book >
22
< book id ="B04" >
23
< name > 紅樓 </ name >
24
< price > 5 </ price >
25
< memo > 四大名著之一。 </ memo >
26
</ book >
27
</ books >
28
29
下面是為Test.java
30
31
import java.io.File;
32
import java.io.FileNotFoundException;
33
import java.io.FileOutputStream;
34
import java.io.IOException;
35
36
import org.w3c.dom. * ;
37
import org.xml.sax.SAXException;
38
39
import javax.xml.parsers. * ;
40
import javax.xml.transform. * ;
41
import javax.xml.transform.dom.DOMSource;
42
import javax.xml.transform.stream. * ;
43
import javax.xml.xpath. * ;
44
45
public class Test
{
46
public static void main(String[] args)
{
47
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
48
Element theBook = null , theElem = null , root = null ;
49
try
{
50
factory.setIgnoringElementContentWhitespace( true );
51
52
DocumentBuilder db = factory.newDocumentBuilder();
53
Document xmldoc = db.parse( new File( " Test1.xml " ));
54
root = xmldoc.getDocumentElement();
55
56
// --- 新建一本書開始 ----
57
theBook = xmldoc.createElement( " book " );
58
theElem = xmldoc.createElement( " name " );
59
theElem.setTextContent( " 新書 " );
60
theBook.appendChild(theElem);
61
62
theElem = xmldoc.createElement( " price " );
63
theElem.setTextContent( " 20 " );
64
theBook.appendChild(theElem);
65
66
theElem = xmldoc.createElement( " memo " );
67
theElem.setTextContent( " 新書的更好看。 " );
68
theBook.appendChild(theElem);
69
root.appendChild(theBook);
70
System.out.println( " --- 新建一本書開始 ---- " );
71
output(xmldoc);
72
// --- 新建一本書完成 ----
73
74
// --- 下面對《哈里波特》做一些修改。 ----
75
// --- 查詢找《哈里波特》----
76
theBook = (Element) selectSingleNode( " /books/book[name='哈里波特'] " , root);
77
System.out.println( " --- 查詢找《哈里波特》 ---- " );
78
output(theBook);
79
// --- 此時修改這本書的價格 -----
80
theBook.getElementsByTagName( " price " ).item( 0 ).setTextContent( " 15 " ); // getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當(dāng)于xpath的".//price"。
81
System.out.println( " --- 此時修改這本書的價格 ---- " );
82
output(theBook);
83
// --- 另外還想加一個屬性id,值為B01 ----
84
theBook.setAttribute( " id " , " B01 " );
85
System.out.println( " --- 另外還想加一個屬性id,值為B01 ---- " );
86
output(theBook);
87
// --- 對《哈里波特》修改完成。 ----
88
89
// --- 要用id屬性刪除《三國演義》這本書 ----
90
theBook = (Element) selectSingleNode( " /books/book[@id='B02'] " , root);
91
System.out.println( " --- 要用id屬性刪除《三國演義》這本書 ---- " );
92
output(theBook);
93
theBook.getParentNode().removeChild(theBook);
94
System.out.println( " --- 刪除后的XML ---- " );
95
output(xmldoc);
96
97
// --- 再將所有價格低于10的書刪除 ----
98
NodeList someBooks = selectNodes( " /books/book[price<10] " , root);
99
System.out.println( " --- 再將所有價格低于10的書刪除 --- " );
100
System.out.println( " --- 符合條件的書有 " + someBooks.getLength() + " 本。 --- " );
101
for ( int i = 0 ;i < someBooks.getLength();i ++ )
{
102
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
103
}
104
output(xmldoc);
105
106
saveXml( " Test1_Edited.xml " , xmldoc);
107
} catch (ParserConfigurationException e)
{
108
e.printStackTrace();
109
} catch (SAXException e)
{
110
e.printStackTrace();
111
} catch (IOException e)
{
112
e.printStackTrace();
113
}
114
}
115
116
public static void output(Node node)
{ // 將node的XML字符串輸出到控制臺
117
TransformerFactory transFactory = TransformerFactory.newInstance();
118
try
{
119
Transformer transformer = transFactory.newTransformer();
120
transformer.setOutputProperty( " encoding " , " gb2312 " );
121
transformer.setOutputProperty( " indent " , " yes " );
122
123
DOMSource source = new DOMSource();
124
source.setNode(node);
125
StreamResult result = new StreamResult();
126
result.setOutputStream(System.out);
127
128
transformer.transform(source, result);
129
} catch (TransformerConfigurationException e)
{
130
e.printStackTrace();
131
} catch (TransformerException e)
{
132
e.printStackTrace();
133
}
134
}
135
136
public static Node selectSingleNode(String express, Object source)
{ // 查找節(jié)點,并返回第一個符合條件節(jié)點
137
Node result = null ;
138
XPathFactory xpathFactory = XPathFactory.newInstance();
139
XPath xpath = xpathFactory.newXPath();
140
try
{
141
result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
142
} catch (XPathExpressionException e)
{
143
e.printStackTrace();
144
}
145
146
return result;
147
}
148
149
public static NodeList selectNodes(String express, Object source)
{ // 查找節(jié)點,返回符合條件的節(jié)點集。
150
NodeList result = null ;
151
XPathFactory xpathFactory = XPathFactory.newInstance();
152
XPath xpath = xpathFactory.newXPath();
153
try
{
154
result = (NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
155
} catch (XPathExpressionException e)
{
156
e.printStackTrace();
157
}
158
159
return result;
160
}
161
162
public static void saveXml(String fileName, Document doc)
{ // 將Document輸出到文件
163
TransformerFactory transFactory = TransformerFactory.newInstance();
164
try
{
165
Transformer transformer = transFactory.newTransformer();
166
transformer.setOutputProperty( " indent " , " yes " );
167
168
DOMSource source = new DOMSource();
169
source.setNode(doc);
170
StreamResult result = new StreamResult();
171
result.setOutputStream( new FileOutputStream(fileName));
172
173
transformer.transform(source, result);
174
} catch (TransformerConfigurationException e)
{
175
e.printStackTrace();
176
} catch (TransformerException e)
{
177
e.printStackTrace();
178
} catch (FileNotFoundException e)
{
179
e.printStackTrace();
180
}
181
}
182
}
183

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45


46


47

48

49


50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101


102

103

104

105

106

107


108

109


110

111


112

113

114

115

116


117

118


119

120

121

122

123

124

125

126

127

128

129


130

131


132

133

134

135

136


137

138

139

140


141

142


143

144

145

146

147

148

149


150

151

152

153


154

155


156

157

158

159

160

161

162


163

164


165

166

167

168

169

170

171

172

173

174


175

176


177

178


179

180

181

182

183
