# 1. SAXReader reader = new SAXReader(); # 2. Document doc = reader.read(...); # 3. List childNodes = doc.selectNodes("//Config/Child/ChildNode"); # 4. for(Object obj:childNodes) { # 5. Node childNode = (Node)obj; # 6. # 7. String name = childNode.valueOf("@name"); # 8. String text = childNode.getText(); # 9. } # 10. # 11. # 12. # 13. 一.Document对象相关 # 14. # 15. 1.读取XML文件,获得document对象. # 16. SAXReader reader = new SAXReader(); # 17. Document document = reader.read(new File("input.xml")); # 18. # 19. 2.解析XML形式的文本,得到document对象. # 20. String text = "<members></members>"; # 21. Document document = DocumentHelper.parseText(text); # 22. 3.主动创建document对象. # 23. Document document = DocumentHelper.createDocument(); # 24. Element root = document.addElement("members");// 创建根节点 # 25. 二.节点相关 # 26. # 27. 1.获取文档的根节点. # 28. Element rootElm = document.getRootElement(); # 29. 2.取得某节点的单个子节点. # 30. Element memberElm=root.element("member");// "member"是节点名 # 31. 3.取得节点的文字 # 32. String text=memberElm.getText();也可以用: # 33. String text=root.elementText("name");这个是取得根节点下的name字节点的文字. # 34. # 35. 4.取得某节点下名为"member"的所有字节点并进行遍历. # 36. List nodes = rootElm.elements("member"); # 37. # 38. for (Iterator it = nodes.iterator(); it.hasNext();) { # 39. Element elm = (Element) it.next(); # 40. // do something # 41. } # 42. 5.对某节点下的所有子节点进行遍历. # 43. for(Iterator it=root.elementIterator();it.hasNext();){ # 44. Element element = (Element) it.next(); # 45. // do something # 46. } # 47. 6.在某节点下添加子节点. # 48. Element ageElm = newMemberElm.addElement("age"); # 49. 7.设置节点文字. # 50. ageElm.setText("29"); # 51. 8.删除某节点. # 52. parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点 # 53. 9.添加一个CDATA节点. # 54. Element contentElm = infoElm.addElement("content"); # 55. contentElm.addCDATA(diary.getContent()); # 56. # 57. 三.属性相关. # 58. 1.取得某节点下的某属性 # 59. Element root=document.getRootElement(); # 60. Attribute attribute=root.attribute("size");// 属性名name # 61. 2.取得属性的文字 # 62. String text=attribute.getText();也可以用: # 63. String text2=root.element("name").attributeValue("firstname");这个是取得根节点下name字节点的属性firstname的值. # 64. # 65. 3.遍历某节点的所有属性 # 66. Element root=document.getRootElement(); # 67. for(Iterator it=root.attributeIterator();it.hasNext();){ # 68. Attribute attribute = (Attribute) it.next(); # 69. String text=attribute.getText(); # 70. System.out.println(text); # 71. } # 72. 4.设置某节点的属性和文字. # 73. newMemberElm.addAttribute("name", "sitinspring"); # 74. 5.设置属性的文字 # 75. Attribute attribute=root.attribute("name"); # 76. attribute.setText("sitinspring"); # 77. 6.删除某属性 # 78. Attribute attribute=root.attribute("size");// 属性名name # 79. root.remove(attribute); # 80. 四.将文档写入XML文件. # 81. 1.文档中全为英文,不设置编码,直接写入的形式. # 82. XMLWriter writer = new XMLWriter(new FileWriter("output.xml")); # 83. writer.write(document); # 84. writer.close(); # 85. 2.文档中含有中文,设置编码格式写入的形式. # 86. OutputFormat format = OutputFormat.createPrettyPrint(); # 87. format.setEncoding("GBK"); // 指定XML编码 # 88. XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format); # 89. # 90. writer.write(document); # 91. writer.close(); # 92. 五.字符串与XML的转换 # 93. 1.将字符串转化为XML # 94. String text = "<members> <member>sitinspring</member> </members>"; # 95. Document document = DocumentHelper.parseText(text); # 96. 2.将文档或节点的XML转化为字符串. # 97. SAXReader reader = new SAXReader(); # 98. Document document = reader.read(new File("input.xml")); # 99. Element root=document.getRootElement(); # 100. String docXmlText=document.asXML(); # 101. String rootXmlText=root.asXML(); # 102. Element memberElm=root.element("member"); # 103. String memberXmlText=memberElm.asXML(); # 104. # 105. # 106. # 107. # 108. dom4j API 包含一个解析 XML 文档的工具。本文中将使用这个解析器创建一个示例 XML 文档。清单 1 显示了这个示例 XML 文档,catalog.xml。 # 109. # 110. 清单 1. 示例 XML 文档(catalog.xml) # 111. <?xml version="1.0" encoding="UTF-8"?> # 112. <catalog> # 113. <!--An XML Catalog--> # 114. <?target instruction?> # 115. <journal title="XML Zone" # 116. publisher="IBM developerWorks"> # 117. <article level="Intermediate" date="December-2001"> # 118. <title>Java configuration with XML Schema</title> # 119. <author> # 120. <firstname>Marcello</firstname> # 121. <lastname>Vitaletti</lastname> # 122. </author> # 123. </article> # 124. </journal> # 125. </catalog> # 126. # 127. # 128. # 129. 然后使用同一个解析器修改 catalog.xml,清单 2 是修改后的 XML 文档,catalog-modified.xml。 # 130. # 131. 清单 2. 修改后的 XML 文档(catalog-modified.xml) # 132. <?xml version="1.0" encoding="UTF-8"?> # 133. <catalog> # 134. <!--An XML catalog--> # 135. <?target instruction?> # 136. <journal title="XML Zone" # 137. publisher="IBM developerWorks"> # 138. <article level="Introductory" date="October-2002"> # 139. <title>Create flexible and extensible XML schemas</title> # 140. <author> # 141. <firstname>Ayesha</firstname> # 142. <lastname>Malik</lastname> # 143. </author> # 144. </article> # 145. </journal> # 146. </catalog> # 147. # 148. # 149. # 150. 与 W3C DOM API 相比,使用 dom4j 所包含的解析器的好处是 dom4j 拥有本地的 XPath 支持。DOM 解析器不支持使用 XPath 选择节点。 # 151. # 152. 本文包括以下几个部分: # 153. # 154. 预先设置 # 155. 创建文档 # 156. 修改文档 # 157. 预先设置 # 158. # 159. 这个解析器可以从 http://dom4j.org 获取。通过设置使 dom4j-1.4/dom4j-full.jar 能够在 classpath 中访问,该文件中包括 dom4j 类、 XPath 引擎以及 SAX 和 DOM 接口。如果已经使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向 classpath 中增加 dom4j-1.4/dom4j.jar 。 dom4j.jar 包括 dom4j 类和 XPath 引擎,但是不含 SAX 与 DOM 接口。 # 160. # 161. # 162. # 163. # 164. # 165. # 166. 回页首 # 167. # 168. # 169. # 170. # 171. 创建文档 # 172. # 173. 本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。 # 174. # 175. 使用 import 语句导入 dom4j API 类: # 176. # 177. import org.dom4j.Document; # 178. import org.dom4j.DocumentHelper; # 179. import org.dom4j.Element; # 180. # 181. # 182. # 183. 使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。 # 184. # 185. Document document = DocumentHelper.createDocument(); # 186. # 187. # 188. 使用 addElement() 方法创建根元素 catalog 。 addElement() 用于向 XML 文档中增加元素。 # 189. # 190. Element catalogElement = document.addElement("catalog"); # 191. # 192. # 193. 在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。 # 194. # 195. catalogElement.addComment("An XML catalog"); # 196. # 197. # 198. 在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。 # 199. # 200. catalogElement.addProcessingInstruction("target","text"); # 201. # 202. # 203. 在 catalog 元素中使用 addElement() 方法增加 journal 元素。 # 204. # 205. Element journalElement = catalogElement.addElement("journal"); # 206. # 207. # 208. 使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。 # 209. # 210. journalElement.addAttribute("title", "XML Zone"); # 211. journalElement.addAttribute("publisher", "IBM developerWorks"); # 212. # 213. # 214. 向 article 元素中添加 journal 元素。 # 215. # 216. Element articleElement=journalElement.addElement("article"); # 217. # 218. # 219. 为 article 元素增加 level 和 date 属性。 # 220. # 221. articleElement.addAttribute("level", "Intermediate"); # 222. articleElement.addAttribute("date", "December-2001"); # 223. # 224. # 225. 向 article 元素中增加 title 元素。 # 226. # 227. Element titleElement=articleElement.addElement("title"); # 228. # 229. # 230. 使用 setText() 方法设置 article 元素的文本。 # 231. # 232. titleElement.setText("Java configuration with XML Schema"); # 233. # 234. # 235. 在 article 元素中增加 author 元素。 # 236. # 237. Element authorElement=articleElement.addElement("author"); # 238. # 239. # 240. 在 author 元素中增加 firstname 元素并设置该元素的文本。 # 241. # 242. Element firstNameElement=authorElement.addElement("firstname"); # 243. firstNameElement.setText("Marcello"); # 244. # 245. # 246. 在 author 元素中增加 lastname 元素并设置该元素的文本。 # 247. # 248. Element lastNameElement=authorElement.addElement("lastname"); # 249. lastNameElement.setText("Vitaletti"); # 250. # 251. # 252. 可以使用 addDocType() 方法添加文档类型说明。 # 253. # 254. document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd"); # 255. # 256. # 257. 这样就向 XML 文档中增加文档类型说明: # 258. # 259. <!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd"> # 260. # 261. # 262. 如果文档要使用文档类型定义(DTD)文档验证则必须有 Doctype。 # 263. # 264. XML 声明 <?xml version="1.0" encoding="UTF-8"?> 自动添加到 XML 文档中。 # 265. # 266. 清单 3 所示的例子程序 XmlDom4J.java 用于创建 XML 文档 catalog.xml。 # 267. # 268. 清单 3. 生成 XML 文档 catalog.xml 的程序(XmlDom4J.java) # 269. import org.dom4j.Document; # 270. import org.dom4j.DocumentHelper; # 271. import org.dom4j.Element; # 272. import org.dom4j.io.XMLWriter; # 273. import java.io.*; # 274. public class XmlDom4J{ # 275. public void generateDocument(){ # 276. Document document = DocumentHelper.createDocument(); # 277. Element catalogElement = document.addElement("catalog"); # 278. catalogElement.addComment("An XML Catalog"); # 279. catalogElement.addProcessingInstruction("target","text"); # 280. Element journalElement = catalogElement.addElement("journal"); # 281. journalElement.addAttribute("title", "XML Zone"); # 282. journalElement.addAttribute("publisher", "IBM developerWorks"); # 283. Element articleElement=journalElement.addElement("article"); # 284. articleElement.addAttribute("level", "Intermediate"); # 285. articleElement.addAttribute("date", "December-2001"); # 286. Element titleElement=articleElement.addElement("title"); # 287. titleElement.setText("Java configuration with XML Schema"); # 288. Element authorElement=articleElement.addElement("author"); # 289. Element firstNameElement=authorElement.addElement("firstname"); # 290. firstNameElement.setText("Marcello"); # 291. Element lastNameElement=authorElement.addElement("lastname"); # 292. lastNameElement.setText("Vitaletti"); # 293. document.addDocType("catalog", # 294. null,"file://c:/Dtds/catalog.dtd"); # 295. try{ # 296. XMLWriter output = new XMLWriter( # 297. new FileWriter( new File("c:/catalog/catalog.xml") )); # 298. output.write( document ); # 299. output.close(); # 300. } # 301. catch(IOException e){System.out.println(e.getMessage());} # 302. } # 303. public static void main(String[] argv){ # 304. XmlDom4J dom4j=new XmlDom4J(); # 305. dom4j.generateDocument(); # 306. }} # 307. # 308. # 309. # 310. 这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。 # 311. # 312. # 313. # 314. # 315. # 316. # 317. 回页首 # 318. # 319. # 320. # 321. # 322. 修改文档 # 323. # 324. 这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。 # 325. # 326. 使用 SAXReader 解析 XML 文档 catalog.xml: # 327. # 328. SAXReader saxReader = new SAXReader(); # 329. Document document = saxReader.read(inputXml); # 330. # 331. # 332. SAXReader 包含在 org.dom4j.io 包中。 # 333. # 334. inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。 # 335. # 336. List list = document.selectNodes("//article/@level" ); # 337. Iterator iter=list.iterator(); # 338. while(iter.hasNext()){ # 339. Attribute attribute=(Attribute)iter.next(); # 340. if(attribute.getValue().equals("Intermediate")) # 341. attribute.setValue("Introductory"); # 342. } # 343. # 344. # 345. 获取 article 元素列表,从 article 元素中的 title 元素得到一个迭代器,并修改 title 元素的文本。 # 346. # 347. list = document.selectNodes("//article" ); # 348. iter=list.iterator(); # 349. while(iter.hasNext()){ # 350. Element element=(Element)iter.next(); # 351. Iterator iterator=element.elementIterator("title"); # 352. while(iterator.hasNext()){ # 353. Element titleElement=(Element)iterator.next(); # 354. if(titleElement.getText().equals("Java configuration with XML Schema")) # 355. titleElement.setText("Create flexible and extensible XML schema"); # 356. }} # 357. # 358. # 359. 通过和 title 元素类似的过程修改 author 元素。 # 360. # 361. 清单 4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文档修改成 catalog-modified.xml 文档。 # 362. # 363. 清单 4. 用于修改 catalog.xml 的程序(Dom4Jparser.java) # 364. import org.dom4j.Document; # 365. import org.dom4j.Element; # 366. import org.dom4j.Attribute; # 367. import java.util.List; # 368. import java.util.Iterator; # 369. import org.dom4j.io.XMLWriter; # 370. import java.io.*; # 371. import org.dom4j.DocumentException; # 372. import org.dom4j.io.SAXReader; # 373. public class Dom4JParser{ # 374. public void modifyDocument(File inputXml){ # 375. try{ # 376. SAXReader saxReader = new SAXReader(); # 377. Document document = saxReader.read(inputXml); # 378. List list = document.selectNodes("//article/@level" ); # 379. Iterator iter=list.iterator(); # 380. while(iter.hasNext()){ # 381. Attribute attribute=(Attribute)iter.next(); # 382. if(attribute.getValue().equals("Intermediate")) # 383. attribute.setValue("Introductory"); # 384. } # 385. # 386. list = document.selectNodes("//article/@date" ); # 387. iter=list.iterator(); # 388. while(iter.hasNext()){ # 389. Attribute attribute=(Attribute)iter.next(); # 390. if(attribute.getValue().equals("December-2001")) # 391. attribute.setValue("October-2002"); # 392. } # 393. list = document.selectNodes("//article" ); # 394. iter=list.iterator(); # 395. while(iter.hasNext()){ # 396. Element element=(Element)iter.next(); # 397. Iterator iterator=element.elementIterator("title"); # 398. while(iterator.hasNext()){ # 399. Element titleElement=(Element)iterator.next(); # 400. if(titleElement.getText().equals("Java configuration with XML # 401. Schema")) # 402. titleElement.setText("Create flexible and extensible XML schema"); # 403. } # 404. } # 405. list = document.selectNodes("//article/author" ); # 406. iter=list.iterator(); # 407. while(iter.hasNext()){ # 408. Element element=(Element)iter.next(); # 409. Iterator iterator=element.elementIterator("firstname"); # 410. while(iterator.hasNext()){ # 411. Element firstNameElement=(Element)iterator.next(); # 412. if(firstNameElement.getText().equals("Marcello")) # 413. firstNameElement.setText("Ayesha"); # 414. } # 415. } # 416. list = document.selectNodes("//article/author" ); # 417. iter=list.iterator(); # 418. while(iter.hasNext()){ # 419. Element element=(Element)iter.next(); # 420. Iterator iterator=element.elementIterator("lastname"); # 421. while(iterator.hasNext()){ # 422. Element lastNameElement=(Element)iterator.next(); # 423. if(lastNameElement.getText().equals("Vitaletti")) # 424. lastNameElement.setText("Malik"); # 425. } # 426. } # 427. XMLWriter output = new XMLWriter( # 428. new FileWriter( new File("c:/catalog/catalog-modified.xml") )); # 429. output.write( document ); # 430. output.close(); # 431. } # 432. # 433. catch(DocumentException e) # 434. { # 435. System.out.println(e.getMessage()); # 436. } # 437. catch(IOException e){ # 438. System.out.println(e.getMessage()); # 439. } # 440. } # 441. public static void main(String[] argv){ # 442. Dom4JParser dom4jParser=new Dom4JParser(); # 443. dom4jParser.modifyDocument(new File("c:/catalog/catalog.xml")); # 444. } # 445. } # 446.