How can I count the number of leaf nodes coming off a particular XML node using jQuery?
The XML in question looks similar to this. I want all leaf nodes coming off the <Errors> node.
<Errors>
<ErrorParentCat>
<ErrorTag/>
<ErrorTag2/>
</ErrorParentCat>
</Errors>
In this example I want <ErrorTag/> and <ErrorTag2/> counted only. The result should therefore be 2. Also <ErrorParentCat> is an example tag, there could be many within <Errors> with different names.
Once I have the number I would like a list of these leaf nodes too, if possible.
Assuming you already have an
XMLDocumentnamedxml:You can also just pass the XML string directly to the jQuery function:
jsfiddle demo →
Edit you said you wanted a list of those leaf nodes. In the code above, you’ve already got them:
Edit #2 as Tim Down has pointed out (see comments below), you cannot just pass the XML string to
$()in IE (!@#$ing IE). You should use the jQuery 1.5 function$.parseXML()to parse an arbitrary well-formed XML string into anXMLDocument:new jsfiddle demo →