|
1. 加載XML文檔: var xmlDom = new ActiveXObject("MSXML2.DOMDocument");
xmlDom.load("filename.xml"); //加載XML文件
2. 訪問節(jié)點(diǎn): var root = xmlDom.documentElement;//獲取根節(jié)點(diǎn)
var nodeList = root.childNodes; //獲取節(jié)點(diǎn)的所有子節(jié)點(diǎn)
var node = nodeList[i];
var name = node.attributes[0].value;//獲取節(jié)點(diǎn)的第一個(gè)屬性的值
var xmlElement = node.xml;//包含起始標(biāo)簽+內(nèi)容+結(jié)束標(biāo)簽
var content = xmlElement.childNodes[0].xml;//若xmlElement不包括子節(jié)點(diǎn),則可以獲得xmlElement標(biāo)簽中的內(nèi)容;若其包括子節(jié)點(diǎn),則獲得第一個(gè)子節(jié)點(diǎn)標(biāo)簽及其內(nèi)容; var content = xmlElement.text;
3. 添加節(jié)點(diǎn): var newElement = xmlDom.createElement("element");
// 創(chuàng)建attribute屬性,并添加到element節(jié)點(diǎn)上
var attribute = xmlDom.createAttribute("attribute");
attribute.value = "attrubuteValue";
newElement.setAttributeNode(name);
// 創(chuàng)建subElement子節(jié)點(diǎn),并添加到newElement節(jié)點(diǎn)上
var subElement = xmlDom.createElement("subElement");
newElement.text = "SubElementContent";
newElement.appendChild(subElement);
//將newElement添加到根節(jié)點(diǎn)下
root.appendChild(newElement);

4. 刪除節(jié)點(diǎn): var node = root.selectSingleNode("xpath");
if (node != null)
root.removeChild(node);
5. 保存節(jié)點(diǎn): xmlDom.save("driver:\\dir\filename.xml");//保存XML文件
6. Xpath幾個(gè)例子: authors
authors/author
authors/author/name
 authors/**//*/name
authors/author/* //*為通配符
authors/author[nationality]/name //用“[]”來限制只選取擁有nationality子節(jié)點(diǎn)的節(jié)點(diǎn)
authors/author[nationality='Russian']/name //進(jìn)一步限制子節(jié)點(diǎn)nationality的值為'Russian'
authors/author[@period="classical"] //選取屬性period為"classical"的節(jié)點(diǎn)
authors/author/@period //選取節(jié)點(diǎn)的屬性
|