user5408508
user5408508

Reputation:

Javascript show how many elements in root XML file

I need this html/javascript file to display HOW MANY elements an XML document has directly under the root element.

This should be showing as:

The root element has this many direct children: 2

Instead, it it showing as:

The root element has this many direct children: 0The root element has this many direct children: 1 

How do I go about this?

This is the code I am using:

 <html land="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script>
            function loadXMLDoc(XML65) {
                xhttp = new XMLHttpRequest();
                xhttp.open("GET", XML65, false);
                xhttp.send();
                return xhttp.responseXML;
            }
        </script>
    </head>
    <body>
        <h1>Testing XML FILE</h1>
        <script>
            var xmlDoc = loadXMLDoc("XML65.xml");

            for (i = 0; i < xmlDoc.childNodes.length; i++)
            {
                thisNode = xmlDoc.childNodes[i];
                document.write("The root element has this many direct children: " + i);

            }
        </script>

    </body>
    </html>

Upvotes: 1

Views: 137

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

your script should be

var xmlDoc = loadXMLDoc("XML65.xml");
document.write("The root element has this many direct children: " + xmlDoc.childNodes.length);

P.S. I would highly recommend familiarising yourself with alternatives to document.write

Upvotes: 1

Related Questions