首页 > 代码库 > DOM解析XML

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 //获得document10 11 Document document=builder.parse("books.xml");//根目录下失误books.xml12 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 //是否是title33 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>

 

DOM解析XML