1 package com.gcli.xml; 2 3 import java.io.IOException; 4 5 import javax.xml.parsers.DocumentBuilder; 6 import javax.xml.parsers.DocumentBuilderFactory; 7 import javax.xml.parsers.ParserConfigurationException; 8 9 import org.w3c.dom.Document; 10 import org.w3c.dom.Element; 11 import org.w3c.dom.NodeList; 12 import org.xml.sax.SAXException; 13 14 public class XMLDOMTest { 15 16 public static void main(String[] args) { 17 // (1)建立DocumentBuilderfactory ,用于取得DocumentBuilder 18 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 19 // (2)通过DocumentBuilderfactory取得DocumentBuilder 20 DocumentBuilder builder = null; 21 try { 22 builder = factory.newDocumentBuilder(); 23 } catch (ParserConfigurationException e) { 24 e.printStackTrace(); 25 } 26 // (3)定义Document接口对象,通过DocumenBuilder类进行DOM树转换操作 27 Document doc = null; 28 try { 29 doc = builder.parse("C:\javatest\bookstore.xml"); 30 } catch (SAXException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 // (4)查找book的节点 36 NodeList nl = doc.getElementsByTagName("book"); 37 // (5)遍历book节点,并输出内容 38 for (int i = 0; i < nl.getLength(); i++) { 39 Element element = (Element) nl.item(i); 40 String category = element.getAttribute("category"); 41 String title = element.getElementsByTagName("title").item(0) 42 .getFirstChild().getNodeValue(); 43 String author = element.getElementsByTagName("author").item(0) 44 .getFirstChild().getNodeValue(); 45 String year = element.getElementsByTagName("year").item(0) 46 .getFirstChild().getNodeValue(); 47 String price = element.getElementsByTagName("price").item(0) 48 .getFirstChild().getNodeValue(); 49 System.out.println("第" + (i + 1) + "本书,类别:" + category + ",名字:" 50 + title + ",作者:" + author + ",出版时间:" + year + ",价格:" 51 + price + "。"); 52 } 53 } 54 55 }
1 <?xml version="1.0" encoding="ISO-8859-1" ?> 2 - <bookstore> 3 - <book category="cooking"> 4 <title lang="en">Everyday Italian</title> 5 <author>Giada De Laurentiis</author> 6 <year>2005</year> 7 <price>30.00</price> 8 </book> 9 - <book category="children"> 10 <title lang="en">Harry Potter</title> 11 <author>J K. Rowling</author> 12 <year>2005</year> 13 <price>29.99</price> 14 </book> 15 - <book category="web"> 16 <title lang="en">XQuery Kick Start</title> 17 <author>James McGovern</author> 18 <author>Per Bothner</author> 19 <author>Kurt Cagle</author> 20 <author>James Linn</author> 21 <author>Vaidyanathan Nagarajan</author> 22 <year>2003</year> 23 <price>49.99</price> 24 </book> 25 - <book category="web" cover="paperback"> 26 <title lang="en">Learning XML</title> 27 <author>Erik T. Ray</author> 28 <year>2003</year> 29 <price>39.95</price> 30 </book> 31 </bookstore>