1这是一个用JAVA W3C DOM 进行XML操作的例子,包含了查询、增加、修改、删除、保存的基本操作。较完整的描述了一个XML的整个操作流程。适合刚入门JAVA XML操作的朋友参考和学习。
2
3假设有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
31import 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")相当于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) { // 查找节点,并返回第一个符合条件节点
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) { // 查找节点,返回符合条件的节点集。
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