[XML]學(xué)習(xí)筆記(九)DOM
來源:程序員人生 發(fā)布時(shí)間:2016-07-11 08:57:54 閱讀次數(shù):2711次
DOM是1個(gè)使程序和腳本有能力動(dòng)態(tài)的訪問和更新文檔的內(nèi)容、結(jié)構(gòu)和樣式的平臺(tái)和語(yǔ)言中立的接口,主要被分為3個(gè)不同的部份:核心DOM、XML DOM和HTML DOM。http://www.w3school.com.cn/xmldom/dom_intro.asp
1、JAXP接口(Java API for XMLParsing)
a) org.w3c.dom W3C推薦的用于XML標(biāo)準(zhǔn)計(jì)劃文檔對(duì)象模型的接口。
b) org.xml.sax 用于對(duì)XML進(jìn)行語(yǔ)法分析的事件驅(qū)動(dòng)的XML簡(jiǎn)單API(SAX)。
c) javax.xml.parsers解析器工廠工具,程序員取得并配置特殊的特殊語(yǔ)法分析器。
2、這3個(gè)包在jdk中都有
3、XML DOM的主要用處:
XML DOM(Document Object Model)即XML文檔對(duì)象模型,它定義了訪問和處理XML文檔的標(biāo)準(zhǔn)方法,或說XML DOM是用于獲得、更改、添加或刪除XML元素的標(biāo)準(zhǔn)。
主要利用于:
1) 在需要修改XML文檔的內(nèi)容、結(jié)構(gòu)溫柔序時(shí);
2) 需要屢次遍歷XML文檔時(shí);
3) 歸并多個(gè)XML文檔時(shí);
4) 對(duì)XML內(nèi)容做復(fù)雜操作。
DOM的工作流程:
DOM解析器將整篇的XML文檔加載到內(nèi)存中,并以樹的情勢(shì)保存,含有豐富的API,所有對(duì)象在DOM中都被看做是Node/節(jié)點(diǎn)。
4、XML DOM解析的基本步驟:
a) 利用程序生成DOM解析器
b) 解析器加載XML
c) 解析器向利用程序返回毛病信息
d) 解析器生成DOM樹
e) 利用程序讀寫DOM樹
f) 利用程序?qū)OM樹轉(zhuǎn)化為XML文檔輸出

5、DOM樹:
a) 抽象的:

b) 真實(shí)的:

6、XML DOM經(jīng)常使用節(jié)點(diǎn)
DOM規(guī)定,XML文檔中的每一個(gè)成份都是1個(gè)節(jié)點(diǎn)
a) Document——全部文檔為1個(gè)文檔節(jié)點(diǎn)documentElement,代表全部文檔,只有1個(gè)元素子節(jié)點(diǎn)root,但可以有多個(gè)其它類型的子節(jié)點(diǎn);
而DocumentFragment表示1個(gè)XML片斷,用于修改DOM樹、截取與合并XML片斷。
b) Element——每一個(gè)XML標(biāo)簽為1個(gè)元素節(jié)點(diǎn);
c) Text——包括在XML元素中的文本是文本節(jié)點(diǎn);注意文本總是存儲(chǔ)在文本節(jié)點(diǎn)中,元素節(jié)點(diǎn)不包括文本,元素節(jié)點(diǎn)的文本也是存儲(chǔ)在文本節(jié)點(diǎn)中的,如<name>CHZH<name>,CHZH不是name的值,而是name具有1個(gè)值為CHZH的文本節(jié)點(diǎn)。
d) Attr——每一個(gè)XML屬性是1個(gè)屬性節(jié)點(diǎn),注意屬性節(jié)點(diǎn)和元素節(jié)點(diǎn)不存在父子關(guān)系;
e) 注釋屬于注釋節(jié)點(diǎn)。

7、解析XML DOM
f) 以下面的JavaScript片斷將books.xml載入了解析器:
xmlDoc=newActiveXObject("Microsoft.XMLDOM"); #創(chuàng)建空的微軟XML文檔對(duì)象
<!--xmlDoc=document.implementation.createDocument("","",null) --> #創(chuàng)建Firefox或其他閱讀器中的空的XML文檔對(duì)象
xmlDoc.async="false";#關(guān)閉異步加載,確保在文檔加載完全前解析器不會(huì)繼續(xù)履行腳本
xmlDoc.load("books.xml");#加載books.xml
load()用于加載文件,而loadXML()用于加載字符串/文本。
1個(gè)跨閱讀器解析XML文檔的實(shí)例:
<html>
<body>
<script type="text/javascript">
try //IE
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load("books.xml");
document.write("xmlDoc is loaded, ready for use");
}
catch(e) {alert(e.message)}
</script>
</body>
</html>
g) 以下面的JavaScript片斷把名為txt的字符串載入解析器:
parser=new DOMParser(); #創(chuàng)建1個(gè)空的XML文檔對(duì)象
xmlDoc=parser.parseFromString(txt,"text/xml"); #告知解析器加載名為txt的字符串
IE使用loadXML()解析XML字符串,方法同上面解析XML文檔的方法,需要?jiǎng)?chuàng)建xmlDoc文檔對(duì)象,并且需要關(guān)閉異步加載;而其他閱讀器使用DOMParser()對(duì)象。
1個(gè)跨閱讀器解析XML字符串的例子:
<html>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Harry Potter</title>";
text=text+"<author>J K. Rowling</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";
try //IE
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
catch(e) {alert(e.message)}
}
document.write("xmlDoc is loaded, ready for use");
</script>
</body>
</html>
8、XML DOM加載函數(shù)
為了不編寫重復(fù)的代碼,將1些代碼存儲(chǔ)在函數(shù)中,并可使用XML DOM加載。如上面的加載XML文檔代碼可定義為loadXMLDoc(dname)函數(shù),存儲(chǔ)在"loadxmldoc.js"文件中:
function loadXMLDoc(dname)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load(dname);
return(xmlDoc);
}
catch(e) {alert(e.message)}
return(null);
}
在使用進(jìn)程中,可以直接援用該函數(shù):
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
#
先創(chuàng)建1個(gè)指向該函數(shù)存儲(chǔ)文件鏈接
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml"); #加載books.xml文檔
document.write("xmlDoc is loaded, ready for use");
</script>
</body>
</html>
9、 XML DOM屬性和方法:設(shè)x為1個(gè)節(jié)點(diǎn)對(duì)象
h)
經(jīng)常使用的屬性:
i.
x.nodeName:x的名稱;
ii.
x.nodeValue:x的文本值;
iii.
x.parentNode:x的父節(jié)點(diǎn);
iv.
x.childNodes:x的子節(jié)點(diǎn);
v. x.attributes:x的屬性節(jié)點(diǎn)。
i)
經(jīng)常使用的方法:
i.
x.getElementsByTagName(name):獲得標(biāo)簽名稱為name的所有元素;
ii.
x.appendChild(node):向x插入子節(jié)點(diǎn)node
iii.
x.removeChild(node):從x刪除子節(jié)點(diǎn)node
如源books.xml為:
<?xml version="1.0" encoding="ISO⑻859⑴"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
通過java程序testDOM.java來對(duì)books.xml進(jìn)行訪問:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class testDOM {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File f = new File("books.xml");
Document doc = builder.parse(f);
Element root = doc.getDocumentElement();
NodeList list = root.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
Element n = (Element) list.item(i);
NamedNodeMap node = n.getAttributes();
for (int x = 0; x < node.getLength(); x++) {
Node nn = node.item(x);
System.out.println(nn.getNodeName() + ": " + nn.getNodeValue());
}
System.out.println("title: " +n.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
System.out.println("author: " + n.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}
}
得到的結(jié)果為:
category:COOKING
title: EverydayItalian
author: Giada DeLaurentiis
category:CHILDREN
title: HarryPotter
author: J K.Rowling
category: WEB
title: XQueryKick Start
author: JamesMcGovern
category: WEB
title: LearningXML
author: Erik T.Ray
10、XML DOM訪問節(jié)點(diǎn)的3種方式:
j) 通過x.getElementByTagName(name)指定節(jié)點(diǎn)標(biāo)簽名的方式訪問,注意該訪問方式為x下所有含有<name>標(biāo)簽的元素,如需訪問全部文檔中所有的<name>元素,則使用xmlDoc.getElementByTagName(name);該方式取得的結(jié)果為1個(gè)節(jié)點(diǎn)列表(NodeList),可以通過下標(biāo)訪問,如x[0]。
k) 通過遍歷節(jié)點(diǎn)樹的方式訪問,如在java中是通過getLength()獲得當(dāng)前NodeList的節(jié)點(diǎn)數(shù),然后使用NodeList.item(i)的方式訪問,其中i為從0起始的下標(biāo);
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{//Process only element nodes (type 1)
document.write(x[i].nodeName);
document.write("<br />");
}
}
l) 通過節(jié)點(diǎn)關(guān)系進(jìn)行訪問,如
x=xmlDoc.getElementsByTagName("book")[0].childNodes;
y=xmlDoc.getElementsByTagName("book")[0].firstChild;
101、 XML DOM獲得節(jié)點(diǎn)信息:
a)
nodeName:規(guī)定節(jié)點(diǎn)的名稱:
i.
nodeName是只讀的;
ii.
元素節(jié)點(diǎn)的nodeName即標(biāo)簽名;
iii.
屬性節(jié)點(diǎn)的nodeName即屬性名;
iv.
文本節(jié)點(diǎn)的nodeName即#text;
v. 文檔節(jié)點(diǎn)的nodeName即#document。
b)
nodeValue:規(guī)定節(jié)點(diǎn)的值:
i.
nodeValue可修改,可以通過直接的賦值語(yǔ)句更改;
ii.
元素節(jié)點(diǎn)的nodeValue為undefined;
iii.
屬性節(jié)點(diǎn)的nodeValue為屬性值;
iv.
本文節(jié)點(diǎn)的nodeValue為文本內(nèi)容;
c) nodeType:規(guī)定節(jié)點(diǎn)的類型,只讀。
元素類型
|
節(jié)點(diǎn)類型
|
元素
|
1
|
屬性
|
2
|
文本
|
3
|
注釋
|
8
|
文檔
|
9
|
102、 Node List節(jié)點(diǎn)列表
a)
Node List對(duì)象會(huì)保持更新,每當(dāng)添加或刪除元素后,列表信息都會(huì)被更新;
b)
取得屬性列表Attribute List:如xmlDoc.getElementsByTagName('book')[0].attributes,與節(jié)點(diǎn)列表相同,會(huì)保持更新。
103、 DOM中的空白與換行
XML 常常在節(jié)點(diǎn)之間含有換行或空白字符,F(xiàn)irefox和其他1些閱讀器,會(huì)把空白或換行作為文本節(jié)點(diǎn)來處理,而 Internet Explorer則不會(huì)。
如果需要疏忽元素節(jié)點(diǎn)之間的空文本節(jié)點(diǎn),則需要進(jìn)行節(jié)點(diǎn)類型檢查,只對(duì)nodeType為1的節(jié)點(diǎn)進(jìn)行處理。
functionget_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
104、 XML DOM節(jié)點(diǎn)值操作:
a)
元素節(jié)點(diǎn)操作:
i.
獲得:nodeValue屬性用于獲得節(jié)點(diǎn)的文本節(jié)點(diǎn)(1般也將文本節(jié)點(diǎn)稱為該節(jié)點(diǎn)的子節(jié)點(diǎn))的值;
ii.
修改:可以通過為nodeValue直接賦值進(jìn)行更改值操作。
iii.
刪除:可以通過parentNode.removeChild(childNode)來刪除parentNode下的childNode節(jié)點(diǎn),刪除1個(gè)節(jié)點(diǎn)后其所有的子節(jié)點(diǎn)都會(huì)被刪除。removeChild()一樣可以用來刪除文本節(jié)點(diǎn),固然,對(duì)文本節(jié)點(diǎn)直接賦值為""也可得到刪除的效果。
iv.
替換:x.replaceChild(origNode, newNode),其中x為文檔的根節(jié)點(diǎn)xmlDoc.documentElement。
v.
創(chuàng)建:xmlDoc.createElement(nodeName),創(chuàng)建1個(gè)名為nodeName的節(jié)點(diǎn)。
vi.
添加:parentNode.appendChild(childNode) 方法向已存在的節(jié)點(diǎn)添加子節(jié)點(diǎn)。parentNode.insertBefore(newChildNode,selectedNode) 方法用于在parentNode的子節(jié)點(diǎn)selectedNode之前插入節(jié)點(diǎn)newChildNode,如果子節(jié)點(diǎn)參數(shù)為null,則插到最后1個(gè)子節(jié)點(diǎn)后面,與appendChild()功能相同。
vii.
克隆:newNode=oldNode.cloneNode(true|false),true和false表示新的節(jié)點(diǎn)是不是克隆源節(jié)點(diǎn)的所有屬性和子節(jié)點(diǎn)。
如:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];#y為第1個(gè)title的文本節(jié)點(diǎn)
txt=x.nodeValue; #txt為文本元素
x.removeChild(y);
b)
屬性節(jié)點(diǎn)操作:
i.
獲得:getAttribute()方法返回屬性的值。
ii.
修改:setAttribute(attrName, newValue)方法用于設(shè)置屬性的值,如果attrName不存在,則創(chuàng)建1個(gè)attrName屬性,并將值賦為newValue。固然,也能夠在獲得屬性節(jié)點(diǎn)后直接通過nodeValue進(jìn)行賦值操作修改其值。
iii.
刪除:removeAttribute(attrName)可以用于刪除指定的屬性。
iv.
創(chuàng)建:xmlDoc.createAttribute(attrName),創(chuàng)建1個(gè)名為attrName的屬性,設(shè)為newAttr,然后可以通過newAttr.nodeValue設(shè)置屬性值。通過對(duì)某個(gè)元素節(jié)點(diǎn)x可以通過x.setAttributeNode(newAttr)的方式添加屬性。除此以外,利用setAttribute()可以直接創(chuàng)建沒有出現(xiàn)過的屬性。
v.
添加:通過x.setAttributeNode(newAttr)的方式添加屬性。
如:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;
c) 文本節(jié)點(diǎn)操作:
vi. 創(chuàng)建:xmlDoc.createTextNode(textValue),創(chuàng)建1個(gè)值為textValue的文本節(jié)點(diǎn)。
vii. 替換:x.replaceData(offset, length, string),x為文本節(jié)點(diǎn),其中offset表示從何處開始替換,以0開始;length表示被替換的字符個(gè)數(shù);string表示新的要插入的字符串。固然,通過nodeValue也能夠完成替換操作。
viii. 添加:x.insertData(offset, string),x為文本節(jié)點(diǎn),其中offset表示從何處添加,以0開始;string表示新的要插入的字符串。
d) CDATA Section節(jié)點(diǎn)操作:
ix. 創(chuàng)建:xmlDoc.createCDATASection(CDATAValue),創(chuàng)建1個(gè)值為CDATAValue的CDATA Section節(jié)點(diǎn)。
e) 注釋節(jié)點(diǎn)操作:
x. 創(chuàng)建:xmlDoc.createComment(commentValue),創(chuàng)建1個(gè)值為commentValue的注釋節(jié)點(diǎn)。
105、 XML DOM解析器的生成(4步):
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();#生成實(shí)例,工廠模式類似于new,但比new靈活,見http://blog.csdn.net/cristianojason/article/details/51510093
Factory.setValidating(false);#設(shè)定解析選項(xiàng)
DocumentBuilder builder = factory.newDocumentBuilder();#從factory中生成builder
Document doc = builder.parse(xmlFileURL);#解析文檔
XMLDOM遍歷解析樹:
Element root = doc.getDocumentElement();#取得root實(shí)例
NodeList children = root.getChildNodes();#取得所有節(jié)點(diǎn)
106、 構(gòu)造新的DOM樹(5步):
Document newDoc = DocumentBuilder.newDocument();#定義新的Document
Element newRoot = newDoc.createElement(“rootName”);#建立新的根節(jié)點(diǎn)newRoot
#第3步自頂向下的構(gòu)建分支
#第4步插入分支
newDoc.appendChild(newRoot)#第5步將newRoot插入到newDoc
107、 XML DOM進(jìn)行文檔歸并:
a) 解析兩個(gè)文檔;
b) import被歸并文檔;
c) 將被歸并文檔的節(jié)點(diǎn)插入目標(biāo)文檔的適當(dāng)位置;
如:
Document doc1 = builder.parse(xmlFileURL1);
Document doc2 = builder.parse(xmlFileURL2);
Element root1 = doc1.getDocumentElement();
Element root2 = doc2.getDocumentElement();
NodeList children = root1.getChildNodes();
for(int i = 0; i < children.getLength(); i++) {
Element newChild = (Element)children.item(i);
Node newImportedChild = doc1.importNode(newChild, true);
root1.appendChild(newImportedChild);
}
108、 DOM利用程序:
a) 生成解析器(4步)
i. 定義factory
ii. 配置解析器
iii.生成解析器
iv. 解析文檔
b) 處理毛病和異常
c) 遍歷DOM樹
d) 處理文檔
i. 修改內(nèi)容
ii. 修改結(jié)構(gòu)
iii. 移動(dòng)節(jié)點(diǎn)
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)