开发者

jQuery XML: Count number of leaf nodes

开发者 https://www.devze.com 2023-02-08 02:54 出处:网络
How can I 开发者_开发知识库count the number of leaf nodes coming off a particular XML node using jQuery?

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 XMLDocument named xml:

var $xml = $(xml),
    count = $xml.find('*').filter(function ()
    {
        return $(this).children().length === 0;
    }).length;
console.log(count);

You can also just pass the XML string directly to the jQuery function:

var $xml = $('<Errors><ErrorParentCat><ErrorTag/><ErrorTag2/></ErrorParentCat></Errors>');
// the rest is the same

jsfiddle demo →


Edit you said you wanted a list of those leaf nodes. In the code above, you've already got them:

var $xml = /* whatever */,
    $leafNodes = $xml.find('*').filter(function ()
    {
        return $(this).children().length === 0;
    }),
    count = $leafNodes.length;

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 an XMLDocument:

var xmlDoc = $.parseXML('<Errors><ErrorParentCat><ErrorTag/><ErrorTag2/></ErrorParentCat></Errors>'),
    $xml = $(xmlDoc);
/* the rest is unchanged */

new jsfiddle demo →


Loads of ways to do this:

var countThem = 0;

    jQuery.ajax({
        type: "GET",
        url: 'blahblah.xml',
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
            var xml2 = load_xml(xml);
            $(xml2).find('Errors').each(function(){
                $(xml2).find('ErrorParentCat').each(function(){
                    alert($(this).text()); //alert the contents
                    countThem++;
                });
            });
            alert(countThem); //alert the total number
        }
    });

and the XML load function:

function load_xml(msg) {   
     if ( typeof msg == 'string') {
        if (window.DOMParser)//Firefox
          {
            parser=new DOMParser();
            data=parser.parseFromString(text,"text/xml");
        }else{ // Internet Explorer
           data=new ActiveXObject("Microsoft.XMLDOM");
           data.async="false";
           data.loadXML(msg);
       }
     } else {
        data = msg;
     }
    return data;
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消