Document.getElementsByTagName(tagName)
The getElementsByTagName method returns a NodeList
collection of those elements with the tag name specified as the argument.
If you use the value "*" as the argument, then a list of
all elements is returned.
In the following example we first load the 'passeriformes.xml' file,
which details the bird species in that order, and then create a NodeList
of all the 'species' elements. The code then iterates through the collection
displaying the value of each firstChild
node (the text node).
XML:
<passeriformes>
<family>
<f_name>Alaudidae</f_name>
<species>Woodlark</species>
<species>Skylark</species>
<species>Shore
Lark</species>
</family>
<family>
<f_name>Motacillidae</f_name>
<species>Rock
Pipit</species>
<species>Water
Pipit</species>
<species>Yellow
Wagtail</species>
</family>
<family>
<f_name>Turdidae</f_name>
<species>Robin</species>
<species>Nightingale</species>
<species>Blackbird</species>
</family>
</passeriformes>
Code (JavaScript):
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("passeriformes.xml");
var i, n_elems, elems = xml_doc.getElementsByTagName("species");
n_elems = elems.length;
for (i = 0; i < n_elems; i++)
document.write(elems[i].firstChild.nodeValue + "<br>");
Output:
Woodlark
Skylark
Shore Lark
Rock Pipit
Water Pipit
Yellow Wagtail
Robin
Nightingale
Blackbird
|