Q1tum wrote:
<?xml version="1.0" encoding="iso-8859-1"?>
<cms>
<num>21</num>
<xmlnames>
<field>id</field>
<field>name</field>
<field>availablefrom</field>
<field>availableuntill</field>
<field>owner</field>
</xmlnames>
</cms>
If I use the following to get te amount of childs for xmlnames I get an
amount of 11:
xmlObj.responseXML.getElementsByTagName('xmlnames' )[0].childNodes.length
Is this wrong or maybe there is a better / other way of counting the
child amount?
childNodes contains all kind of nodes and in your case there a text
nodes with white space between the element nodes e.g. you have
<xmlnames>^^^^^white space text node here
^^^^^ <field>id</field>^^^^ and here
^^^^^ <field>name</field>^^^^ and here ^^^^
</xmlnames>
and not
<xmlnames><field>id</field><field>name</field></xmlnames>
If you are looking only for element nodes then depending on what you
need and depending on the structure of the XML you need to loop through
childNodes and check for nodeType == 1 or you can use
getElementsByTagName('*') or in your case simply
xmlObj.responseXML.getElementsByTagName('xmlnames' )[0].getElementsByTagName('field')
Be aware that getElementsByTagName finds all descendant elements so with
nested structures it is not equivalent to childNodes and checking
nodeType == 1.
But in many cases including your example file when people run into white
space text nodes issues with childNodes then simply switching to
getElementsByTagName to find the elements needed works without problems.
Besides that there is also XPath and NodeFilter/TreeWalker APIs but
support for that is not as wide spread as childNodes/nodeType and
getElementsByTagName and XPath for instance is supported in MSXML 3 and
later for IE/Win and in Mozilla but the APIs are very different.
--
Martin Honnen
http://JavaScript.FAQTs.com/