XML DOM nodeName 属性
XML基础 2023-08-12 18:11:29小码哥的IT人生shichen
XML DOM nodeName 属性
定义和用法
nodeName 属性可返回节点的名称,根据其类型。
语法:
nodeObject.nodeName
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段可显示根节点的节点名称和节点类型:
xmlDoc=loadXMLDoc("books.xml");
document.write("Nodename: " + xmlDoc.nodeName
);
document.write(" (nodetype: " + xmlDoc.nodeType);
输出:
Nodename: #document (nodetype: 9)
TIY
完整实例【显示所有元素的节点名称和节点类型】:
<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");
document.write("Nodename: " + xmlDoc.nodeName);
document.write(" (nodetype: " + xmlDoc.nodeType + ")<br />");
var x=xmlDoc.documentElement;
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType + ")<br />");
var y=x.childNodes;
for (i=0;i<y.length;i++)
{
document.write("Nodename: " + y[i].nodeName);
document.write(" (nodetype: " + y[i].nodeType + ")<br />");
for (z=0;z<y[i].childNodes.length;z++)
{
document.write("Nodename: " + y[i].childNodes[z].nodeName);
document.write(" (nodetype: " + y[i].childNodes[z].nodeType + ")<br />");
}
}
</script>
</body>
</html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
完整实例【显示所有元素的节点名称和节点值】:
<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");
document.write("Nodename: " + xmlDoc.nodeName);
document.write(" (value: " + xmlDoc.childNodes[0].nodeValue + ")<br />");
var x=xmlDoc.documentElement;
document.write("Nodename: " + x.nodeName);
document.write(" (value: " + x.childNodes[0].nodeValue + ")<br />");
var y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
document.write("Nodename: " + y[i].nodeName);
document.write(" (value: " + y[i].childNodes[0].nodeValue + ")<br />");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{
document.write("Nodename: " + y[i].childNodes[z].nodeName);
document.write(" (value: " + y[i].childNodes[z].childNodes[0].nodeValue + ")<br />");
}
}
}
}
</script>
</body>
</html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html