DOM解析XML

DEMO

1
List booklist=new ArrayList(); 2 String id=""; 3 String title=""; 4 String price=""; 5 //获得实例工厂 6 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 7 //获得解析 8 DocumentBuilder builder=factory.newDocumentBuilder(); 9 //获得document 10 11 Document document=builder.parse("books.xml");//根目录下失误books.xml 12 13 14 //获取所有book结点 15 NodeList element=document.getElementsByTagName("book"); 16 //遍历book结点 17 for (int i = 0; i < element.getLength(); i++) { 18 //获取每一个book结点 19 Node node=element.item(i); 20 //结点转换为元素 21 Element bookElement=(Element)node; 22 id=bookElement.getAttribute("id"); 23 //获取所有孩子结点 24 NodeList childNodeList=bookElement.getChildNodes(); 25 //遍历结点 26 for (int c = 0; c < childNodeList.getLength(); c++) { 27 Node cNode=childNodeList.item(c); 28 //获取结点名字 29 30 String cName=cNode.getNodeName(); 31 32 //是否是title 33 if("title".equals(cName)) 34 { 35 title=cNode.getTextContent(); 36 37 } 38 if("price".equals(cName)) 39 { 40 price=((Element)cNode).getAttribute("unit"); 41 price+=cNode.getTextContent(); 42 } 43 44 45 } 46 47 48 book bo=new book(); 49 bo.setId(id); 50 bo.setName(title); 51 bo.setPrice(price); 52 53 booklist.add(bo);//添加到list中
 XML文件

1
<?xml version="1.0" encoding="UTF-8"?> 2 <books> 3 <book id="b001"> 4 <title>Java Core</title> 5 <price>34</price> 6 </book> 7 <book id="b002"> 8 <title>Thinking in Java</title> 9 <price unit="¥">98</price> 10 </book> 11 </books>
原文地址:https://www.cnblogs.com/liuwt365/p/4079242.html