XML DOM item() 方法
XML基础 2023-08-13 19:42:25小码哥的IT人生shichen
XML DOM item() 方法
定义和用法
item() 方法可返回节点列表中处于指定索引号的节点。
语法:
item(index)
参数 | 描述 |
---|---|
index | 索引号 |
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
以下代码片段可循环遍历 <book> 元素,并输出 category 属性的值:
xmlDoc=loadXMLDoc("books.xml"); var x=xmlDoc.getElementsByTagName('book'); for(i=0;i<x.length;i++) { var att=x.item(i).attributes.getNamedItem("category")
; document.write(att.value + "<br />") }
输出:
COOKING CHILDREN WEB WEB
TIY
完整实例【item() - 循环遍历节点列表中的项目】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); var 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>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
完整实例【getNamedItem() - 取得某个项目的值】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); var x=xmlDoc.getElementsByTagName('book'); for(i=0;i<x.length;i++) { var att=x.item(i).attributes.getNamedItem("category"); document.write(att.value + "<br />") } </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
完整实例【getNamedItem() - 改变某个项目的值】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); var x=xmlDoc.getElementsByTagName("book"); for(i=0;i<x.length;i++) { var attlist=x.item(i).attributes; var 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>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html