参考:http://www.w3school.com.cn/xmldom/index.asp
<script type="text/javascript">
// 加载xml文档
loadXML =
function (xmlFile) {
var xmlDoc;
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.load(xmlFile);
} else if (document.implementation&&document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument('', '', null);
xmlDoc.load(xmlFile);
} else{
return null;
}
return xmlDoc;
}
// 首先对xml对象进行判断
checkXMLDocObj =
function (xmlFile) {
var xmlDoc = loadXML(xmlFile);
if (xmlDoc==null) {
alert('您的浏览器不支持xml文件读取,于是本页面禁止您的操作,推荐使用IE5.0以上可以解决此问题!');
window.location.href='/Index.aspx';
}
return xmlDoc;
}
// 然后开始获取需要的Login/Weapon/W的第一个节点的属性值
var xmlDoc = checkXMLDocObj('/EBS/XML/Login.xml');
var v = xmlDoc.getElementsByTagName('Login/Weapon/W')[0].childNodes.getAttribute('Text');
initializeSelect =
function (oid, xPath) {
var xmlDoc = checkXMLDocObj('/EBS/XML/Login.xml');
var n;
var l;
var e = $(oid);
if (e!=null) {
n = xmlDoc.getElementsByTagName(xPath)[0].childNodes;
l = n.length;
for (var i=0; i<l; i++) {
var option = document.createElement('option');
option.value = n[i].getAttribute('Value');
option.innerHTML = n[i].getAttribute('Text');
e.appendChild(option);
}
}
}
</script>
<script type="text/javascript">
var doc = new ActiveXObject("MSXML2.DOMDocument");
function writeXML() {
// var doc = new ActiveXObject("Msxml2.DOMDocument");
// doc.load("tmp.xml");
var doc = new ActiveXObject("MSXML2.DOMDocument");
var p = doc.createProcessingInstruction("xml","version='1.0' encoding='gb2312'");
doc.appendChild(p);
var root = doc.createNode(1,"中国","");
doc.appendChild(root);
var elem=doc.createNode(1,"省","");
root.appendChild(elem);
var att=doc.createAttribute("名称");
att.value="福建";
elem.setAttributeNode(att);
var ele1=doc.createNode(1,"城市","");
ele1.text="厦门";
elem.appendChild(ele1);
var ele2=doc.createNode(1,"城市","");
ele2.text="石狮";
elem.appendChild(ele2);
var ele3=doc.createNode(1,"城市","");
ele3.text="晋江";
elem.appendChild(ele3);
var elem=doc.createNode(1,"省","");
root.appendChild(elem);
var att=doc.createAttribute("名称");
att.value="江苏";
elem.setAttributeNode(att);
var elem=doc.createNode(1,"省","");
root.appendChild(elem);
var att=doc.createAttribute("名称");
att.value="安徽";
elem.setAttributeNode(att);
doc.save("c://china.xml");
}
function readXML() {
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.load ("c://china.xml")
var list = doc.selectNodes("/中国/省[@名称='福建']/城市")
for (var i=0;i<list.length;i++) {
alert(list[i].text);
}
}
</script>
<input type=button value="写入XML" onclick="writeXML()" id=button1 name=button1>
<input type=button value="读取XML" onclick="readXML()" id=button2 name=button2>