首页 > 代码库 > Dom解析xml

Dom解析xml

 1 package cn.pinnsvin;
 2 
 3 import javax.xml.parsers.DocumentBuilder;
 4 import javax.xml.parsers.DocumentBuilderFactory;
 5 
 6 import org.junit.Test;
 7 import org.w3c.dom.Document;
 8 import org.w3c.dom.Node;
 9 import org.w3c.dom.NodeList;
10 
11 //Dom解析Xml
12 public class DomParseTest {
13     
14     @Test
15     public void domParse() throws Exception{
16         //获取DocumentBuilderFactory
17         DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
18         //获取DocumentBuilder
19         DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
20         //通过documentBuilder解析xml文档获得Document对象
21         Document document = documentBuilder.parse("book.xml");
22         //通过元素的名字可以找到元素的集合
23         NodeList nodeList = document.getElementsByTagName("书名");
24         //找到第二个元素
25         Node node = nodeList.item(1);
26         //读出对应节点的文本内容
27         String content = node.getTextContent();
28         System.out.println(content);
29     }
30 }

 

Dom解析xml