1. 程式人生 > >DOM的概念和簡單應用:使用DOM解析XML數據

DOM的概念和簡單應用:使用DOM解析XML數據

rop 手機 實例 des dna 文檔轉換 .get val oms

概念:DOM是Document Object Model的簡稱,即文檔數據模型。

Oracle公司提供了JAXP(Java API for XML Processing)來解析XML。JAXP會把XML文檔轉換成一個DOM樹,JAXP的三個包都在JDK中。

org.w3c.dom;W3C推薦的解析文檔的接口

org.xml.sax;使用SAX解析XML文檔的接口

javax.xml.parsers;解析器工廠工具

一、使用DOM解析XML文檔的步驟

1.創建解析器工廠對象,即DocumentBuilderFactory對象

2.由解析器工廠創建解析器對象,即DocumentBuilder對象

3.由解析器對象解析XML文檔構建相應的DOM樹,創建Document對象

4.以Document對象為起點對DOM樹的節點進行增加、刪除、修改、查詢等操作

5.保存XML數據文檔

二、案例

 1 <?xml version="1.0" encoding="GB2312" standalone="no"?>
 2 <PhoneInfo>
 3     <Brand name="華為">
 4         <Type name="P9" />
 5         <Item>
 6             <title>標題信息</title>
 7             <
link>連接</link> 8 <description>描述</description> 9 <pubDate>2016-11-12</pubDate> 10 </Item> 11 </Brand> 12 <Brand name="蘋果"> 13 <Type name="iPhone5" /> 14 <Type name="iPhone6" /> 15 </
Brand> 16 <Brand name="SAMSUNG"> 17 <Type name="Note7" /> 18 </Brand> 19 <Brand name="SAMSUNG"> 20 <Type name="Note7" /> 21 </Brand> 22 <Brand name="三星"> 23 <Type name="Note7" /> 24 </Brand> 25 <Brand name="三星"> 26 <Type name="Note7" /> 27 </Brand> 28 </PhoneInfo>

1.使用DOM讀取手機收藏信息

 1 import java.io.IOException;
 2 
 3 import javax.xml.parsers.DocumentBuilder;
 4 import javax.xml.parsers.DocumentBuilderFactory;
 5 import javax.xml.parsers.ParserConfigurationException;
 6 
 7 import org.w3c.dom.Document;
 8 import org.w3c.dom.Element;
 9 import org.w3c.dom.Node;
10 import org.w3c.dom.NodeList;
11 import org.xml.sax.SAXException;
12 
13 /**
14  * DOM解析xml文檔
15  * @author Administrator
16  *
17  */
18 public class PhoneInfoShow {
19 
20     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{
21         //得到DOM解析器的工廠實例
22         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
23         //從DOM工廠獲得DOM解析器
24         DocumentBuilder builder = dbf.newDocumentBuilder();
25         //解析xml文檔,得到一個Document對象,即DOM樹
26         Document phoneInfo = builder.parse("src/PhoneInfo.xml");
27         //得到所有Brand節點列表信息
28         NodeList brandList = phoneInfo.getElementsByTagName("Brand");
29         //循環Brand信息
30         for (int i = 0; i < brandList.getLength(); i++) {
31             //獲取第i個Brand元素信息
32             Node node = brandList.item(i);
33             Element brand = (Element)node;
34             //獲取元素屬性值
35             String brandValue = brand.getAttribute("name");
36             System.out.println("手機品牌:"+brandValue);
37             //獲取brand元素下的所有子元素
38             NodeList types = brand.getElementsByTagName("Type");
39             for (int j = 0; j < types.getLength(); j++) {
40                 /*Node item = types.item(j);
41                 Element type = (Element)item;*/
42                 Element type = (Element)types.item(j);
43                 //獲取子節點屬性值
44                 String typeValue = type.getAttribute("name");
45                 System.out.println("\t型號:"+typeValue);
46             }
47         }
48     }
49 
50 }

2.查找節點信息

 1 /**
 2  * 查找節點信息
 3  * @author Administrator
 4  *
 5  */
 6 public class PhoneInfo03{
 7 
 8     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
 9         //得到DOM解析器工廠
10         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
11         //從DOM工廠獲得DOM解析器
12         DocumentBuilder db = dbf.newDocumentBuilder();
13         //解析XML文檔得到一個DOM樹
14         Document phoneInfo = db.parse(new File("src/PhoneInfo.xml"));
15         //讀取pubDate
16         NodeList list = phoneInfo.getElementsByTagName("pubDate");
17         //pubDate元素節點(轉換)
18         Element pubDateElement = (Element)list.item(0);
19         //讀取文本節點
20         String pubDate = pubDateElement.getFirstChild().getNodeValue();
21         System.out.println(pubDate);
22     }
23 
24 }

三、使用DOM維護XML數據

1.添加信息

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import javax.xml.parsers.ParserConfigurationException;
 7 import javax.xml.transform.OutputKeys;
 8 import javax.xml.transform.Transformer;
 9 import javax.xml.transform.TransformerException;
10 import javax.xml.transform.TransformerFactory;
11 import javax.xml.transform.dom.DOMSource;
12 import javax.xml.transform.stream.StreamResult;
13 
14 import org.w3c.dom.Document;
15 import org.w3c.dom.Element;
16 import org.xml.sax.SAXException;
17 
18 /**
19  * 添加手機收藏信息
20  * @author Administrator
21  *
22  */
23 public class PhoneInfoAdd {
24 
25     public static void main(String[] args) throws TransformerException, SAXException, IOException, ParserConfigurationException {
26         //解析器工廠
27         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
28         //解析器
29         DocumentBuilder db = dbf.newDocumentBuilder();
30         //DOM文檔
31         Document phone = db.parse("src/PhoneInfo.xml");
32         /*創建brand節點*/
33         Element brand = phone.createElement("Brand");
34         brand.setAttribute("name","三星");
35         /*創建type節點*/
36         Element type = phone.createElement("Type");
37         type.setAttribute("name", "Note7");
38         //建立父子關系
39         brand.appendChild(type);
40         Element phoneElement = (Element)phone.getElementsByTagName("PhoneInfo").item(0);
41         phoneElement.appendChild(brand);
42         
43         //保存xml文件
44         /*使用傳輸工廠*/
45         TransformerFactory transformerFactory = TransformerFactory.newInstance();    
46         Transformer transformer = transformerFactory.newTransformer();
47         /*創建數據源*/
48         DOMSource domSource = new DOMSource(phone);
49         /*設置編碼類型*/
50         transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
51         /*創建目標數據*/
52         StreamResult result = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
53         /*把DOM樹轉換為xml文件*/
54         transformer.transform(domSource, result);
55         
56     }
57 
58 }

2.修改信息

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import javax.xml.parsers.ParserConfigurationException;
 7 import javax.xml.transform.OutputKeys;
 8 import javax.xml.transform.Result;
 9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerException;
11 import javax.xml.transform.TransformerFactory;
12 import javax.xml.transform.dom.DOMSource;
13 import javax.xml.transform.stream.StreamResult;
14 
15 import org.w3c.dom.Document;
16 import org.w3c.dom.Element;
17 import org.w3c.dom.NodeList;
18 import org.xml.sax.SAXException;
19 
20 public class PhoneInfoEdit {
21 
22     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
23         //解析xml得到DOM對象
24         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
25         DocumentBuilder db = dbf.newDocumentBuilder();
26         Document phone = db.parse("src/PhoneInfo.xml");
27         //找到修改的菜單
28         NodeList brand = phone.getElementsByTagName("Brand");
29         for (int i = 0; i < brand.getLength(); i++) {
30             Element brandElement = (Element)brand.item(i);
31             //得到Brand的name屬性
32             String brandName = brandElement.getAttribute("name");
33             if ("三星".equals(brandName)) {
34                 brandElement.setAttribute("name","SAMSUNG");
35             }
36         }
37         //保存xml文件
38         TransformerFactory transformerFactory = TransformerFactory.newInstance();
39         Transformer transformer = transformerFactory.newTransformer();
40         /*創建DOM源*/
41         DOMSource xmlSource = new DOMSource(phone);
42         /*設置編碼類型*/
43         transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
44         Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
45         //寫入文件
46         transformer.transform(xmlSource, outputTarget );
47     }
48 
49 }

3.刪除信息

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import javax.xml.parsers.ParserConfigurationException;
 7 import javax.xml.transform.OutputKeys;
 8 import javax.xml.transform.Result;
 9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerException;
11 import javax.xml.transform.TransformerFactory;
12 import javax.xml.transform.dom.DOMSource;
13 import javax.xml.transform.stream.StreamResult;
14 
15 import org.w3c.dom.Document;
16 import org.w3c.dom.Element;
17 import org.w3c.dom.NodeList;
18 import org.xml.sax.SAXException;
19 
20 /**
21  * 刪除節點
22  * @author Administrator
23  *
24  */
25 public class PhoneInfoDel {
26 
27     public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
28         //解析xml文檔
29         DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
30         DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
31         Document phone = documentBuilder.parse("src/PhoneInfo.xml");
32         //找到要刪除的節點
33         NodeList brand = phone.getElementsByTagName("Brand");
34         //通過遍歷Brand找到要刪除的節點
35         for (int i = 0; i < brand.getLength(); i++) {
36             Element brandElement = (Element)brand.item(i);
37             //獲取Brand節點屬性
38             String brandName = brandElement.getAttribute("name");
39             //查找需要的節點
40             if ("SAMSUNG".equals(brandName)) {
41                 //獲取父節點,利用父節點刪除這個節點
42                 brandElement.getParentNode().removeChild(brandElement);
43             }
44         }
45         /*for (int i = 0; i < brand.getLength(); i++) {
46             Element brandElement = (Element)brand.item(i);
47             //得到Brand的name屬性
48             String brandName = brandElement.getAttribute("name");
49             if ("三星".equals(brandName)) {
50                 //修改屬性
51                 brandElement.setAttribute("name","SAMSUNG");
52                 //獲取父節點,利用父節點刪除這個節點
53                 brandElement.getParentNode().removeChild(brandElement);
54             }
55         }*/
56         //寫入xml
57         TransformerFactory transformerFactory = TransformerFactory.newInstance();
58         Transformer transformer = transformerFactory.newTransformer();
59         DOMSource xmlSource = new DOMSource(phone);
60         //設置編碼
61         transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
62         Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
63         transformer.transform(xmlSource, outputTarget);
64         /*TransformerFactory transformerFactory = TransformerFactory.newInstance();
65         Transformer transformer = transformerFactory.newTransformer();
66         創建DOM源
67         DOMSource xmlSource = new DOMSource(phone);
68         設置編碼類型
69         transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
70         Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
71         //寫入文件
72         transformer.transform(xmlSource, outputTarget );*/
73 
74     }
75 
76 }

此外,還可以使用DOM4J解析XML文檔會更加方便。

DOM的概念和簡單應用:使用DOM解析XML數據