DOM解析XML

来源:互联网 发布:绿岸网络很多人离职 编辑:程序博客网 时间:2024/06/03 14:52

XML可以作为一种的简单数据存储。

DOM解析,是将XML中的数据组织成一棵树,树的一个一个节点就是XML文档中的数据。

DOM解析XML流程:

1.建立一个解析器工厂,将来创建解析器。

2.创建XML解析器。

3.创建DOM文档对象,设置doc路径。

4.使用DOM文档对象获取节点列表。

5.将节点列表中的每一个子节点分配给一个节点对象。

6.获取节点的内容。

XML信息:

<?xml version="1.0" encoding="UTF-8"?><pet><dog id="1"><name>yaya</name><health>100</health><love>90</love></dog><dog id="2"><name>ouuu</name><health>99</health><love>100</love></dog></pet>
DOM解析代码:

package example.test;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class DomTest {public static void main(String[] args) {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();try {DocumentBuilder db = dbf.newDocumentBuilder();Document doc = db.parse("C:/Users/Administrator/workspace/Test/src/pet.xml");NodeList nodelist = doc.getElementsByTagName("dog");System.out.println("xml初始化信息为:");for (int i = 0; i < nodelist.getLength(); i++) {Node pet = nodelist.item(i);for (Node node = pet.getFirstChild(); node != null; node = node.getNextSibling()) {if (node.getNodeType() == Node.ELEMENT_NODE) {String name = node.getNodeName();String value = node.getFirstChild().getNodeValue();System.out.println(name);System.out.println(value);}}}} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SAXException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
上面应该注意的一点是获取节点内容的时候

String value = node.getFirstChild().getNodeValue();
为什么会有getFirstChild()这个方法呢,因为XML也把<name>yaya</name>中的“yaya”当作节点元素,所以要先获取这个节点。


0 0