Count XML the Number of Header Tag Elements with JavaScript

DanOLorenz
DanOLorenz used Ask the Experts™
on
What is the JavaScript code to count the number of XML Header tag elements right after the XML file has been read using XmlDoc?

Thanks,

Dan
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
try using XmlDoc.length; this should return the number of nodes in the xml response text.

Author

Commented:
It appears my JavaScript code set up is not compatible with the example:

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('title');

document.write("Number of title elements: " + x.length);

After putting in this code with the my own xml file, I am getting the error: "Object Expect".

Why is this?  Do I need to add an import?  

Thanks,

Dan
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Commented:
im not sure what the code you have before that is but I had to add a function for loadXMLDoc(). My page looks like this. Also this is the link to how to do it, you can use an external js file for the loadXMLDoc function also. http://www.w3schools.com/dom/dom_loadxmldoc.asp 

Make sure the books.xml file is in the same folder as the html file
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
<script type="text/javascript">
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

xmlDoc=loadXMLDoc("books.xml");

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

Open in new window

Commented:
Ignore line 3 unless you are going to put lines 7-20 in a external js file named loadxmldoc.js

Author

Commented:
Excellent help

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial