对 XML 文件中特定节点的出现次数进行计数

Count occurences of a specific node in XML file

本文关键字:文件 XML 节点      更新时间:2023-09-26

我想在JavaScript函数中读取这个XML文件并计算部门节点,有人可以帮我吗?

XML文件:

<Departments>
<Department>
<name>name1</name>
<code>code1</code>
</Department>
<Department>
<name>name2</name>
<code>code2</code>
</Department>
<Department>
<name>name3</name>
<code>code3</code>
</Department>
</Departments>

怎么样

xmldoc.getElementsByTagName("Department").length;

如果您需要一些快速代码来获取 xml:

var xmlHttp =(window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
var url = "departments.xml";
xmlHttp.open('GET', url, false); // syncronous
xmlHttp.send();
var xmlDoc = xmlHttp.responseXML;

Javascript中使用E4X,Departments.Department.length();

只需计算字符串中"<Department>"出现多少次即可。