加载XML文档:
var
xmlDom =
new
ActiveXObject(
"MSXML2.DOMDocument"
);
xmlDom.load(
"filename.xml"
);
//加载XML文件
2. 访问节点:
var
root = xmlDom.documentElement;
//获取根节点
var
nodeList = root.childNodes;
//获取节点的所有子节点
var
node = nodeList[i];
var
name = node.attributes[0].value;
//获取节点的第一个属性的值
var
xmlElement = node.xml;
//包含起始标签+内容+结束标签
var
content = xmlElement.childNodes[0].xml;
//若xmlElement不包括子节点,则可以获得xmlElement标签中的内容;若其包括子节点,则获得第一个子节点标签及其内容;
var
content = xmlElement.text;
3. 添加节点:
var
newElement = xmlDom.createElement(
"element"
);
// 创建attribute属性,并添加到element节点上
var
attribute = xmlDom.createAttribute(
"attribute"
);
attribute.value =
"attrubuteValue"
;
newElement.setAttributeNode(name);
// 创建subElement子节点,并添加到newElement节点上
var
subElement = xmlDom.createElement(
"subElement"
);
newElement.text =
"SubElementContent"
;
newElement.appendChild(subElement);
//将newElement添加到根节点下
root.appendChild(newElement);
4. 删除节点:
var
node = root.selectSingleNode(
"xpath"
);
if
(node !=
null
)
root.removeChild(node);
5. 保存节点:
xmlDom.save(
"driver:\\dir\filename.xml"
);
//保存XML文件
6. Xpath几个例子:
authors
authors/author
authors/author/name
authors
/**/
/*/name
authors/author/*
//*为通配符
authors/author[nationality]/name
//用“[]”来限制只选取拥有nationality子节点的节点
authors/author[nationality=
'Russian'
]/name
//进一步限制子节点nationality的值为'Russian'
authors/author[@period=
"classical"
]
//选取属性period为"classical"的节点
authors/author/@period
//选取节点的属性