XML DOM item() 方法
定义和用法
item() 方法返回节点列表中指定索引处的节点。
语法
item(index)
| 参数 | 描述 |
|---|---|
| index | 索引 |
实例
例子 1
下面的代码将 "books.xml" 加载到 xmlDoc 中,循环遍历 <book> 元素,并打印 category 属性的值:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, att, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName('book');
for (i = 0; i < x.length; i++) {
att = x.item(i).attributes.getNamedItem("category");
txt += att.value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
例子 2
循环遍历节点列表中的项目:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.documentElement.childNodes;
for (i = 0; i < x.length; i++) {
if (x.item(i).nodeType == 1) {
txt += x.item(i).nodeName + "<br>";
}
}
document.getElementById("demo").innerHTML = txt;
}
例子 3
更改项目的值:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, attlist, att, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("book");
// 修改 category 属性的属性值
for (i = 0; i < x.length; i++) {
attlist = x.item(i).attributes;
att = attlist.getNamedItem("category");
att.value = "BESTSELLER";
}
// 输出所有 title 和 edition
for (i = 0; i < x.length; i++) {
txt += x[i].getAttribute("category") + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}