dd

XML DOM item() 方法


定义和用法

item() 方法返回节点列表中指定索引号的节点。

语法

item(index)


参数描述
index索引。

实例

下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,循环遍历 <book> 元素并打印 category 属性的值:

实例

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');

for(i=0;i<x.length;i++)
{
att=x.item(i).attributes.getNamedItem("category");
document.write(att.value + "
");
}

上面的代码将输出:

COOKING
CHILDREN
WEB
WEB
 

尝试一下 Demos

item() - 循环遍历节点列表中的项目

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;

for (i=0;i<x.length;i++)
{
//Display only element nodes
if (x.item(i).nodeType==1)
  {
  document.write(x.item(i).nodeName);
  document.write("<br>");
  }
}
</script>
</body>
</html>

getNamedItem() - 改变某个项目的值

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
attlist=x.item(i).attributes;
att=attlist.getNamedItem("category");
att.value="BESTSELLER";
}

//Output all attribute values
for (i=0;i<x.length;i++)
{
document.write(x[i].getAttribute('category'));
document.write("<br>");
}
</script>
</body>
</html>