Tinman
Tinman

Reputation: 31

Can't find node of imported xml file

After importing an XML file I am trying to get the length of the "sheet" nodes but they are returned as 0 when there should be 3 of them. Any help with getting this to work would be appreciated. Thanks.

 $(document).ready(function ()
        {
            $.ajax({
                type: "GET", url: "menu5.xml", dataType: "xml",
                success: function (xml2)
                {
                    var xml = xml2,
                            xmlDoc = $.parseXML(xml),
                            $xml = $(xmlDoc);

                    alert($xml.find('sheet').length);

                    $xml.find('sheet').each(function ()
                    {
                        alert("here2");
                        var sheet = $(this);
                        var menuName = $(sheet).attr("name");
                        alert(menuName);
                    });
                }
            });

Here is the XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<sheet id="1" name="Submenu1">
    <row id="1_1">
        <col1>CODE1a</col1>
        <col2>Option NAME 1</col2>
    </row>
    <row id="1_2">
        <col1>CODE1b</col1>
        <col2>Option NAME 2</col2>
    </row>
</sheet>
<sheet id="2" name="Submenu2">
    <row id="2_1">
        <col1>CODE2a</col1>
        <col2>Option NAME 1</col2>
    </row>
    <row id="2_2">
        <col1>CODE2b</col1>
        <col2>Option NAME 2</col2>
    </row>
</sheet>
<sheet id="3"  name="Submenu3">
    <row id="3_1">
        <col1>CODE3a</col1>
        <col2>Option NAME 1</col2>
    </row>
    <row id="3_2">
        <col1>CODE3b</col1>
        <col2>Option NAME 2</col2>
    </row>
</sheet>
</root>

Upvotes: 1

Views: 31

Answers (1)

Eskay
Eskay

Reputation: 49

As DataType is set to xml, the xml2 variable is already parsed. Thus, remove the xmlDoc step. the following code works :

$.ajax({
            type: "GET", url: "menu5.xml", dataType: "xml",
            success: function (xml2)
            {
                var xml = xml2,
                        /*xmlDoc = $.parseXML(xml),*/
                        $xml = $(xml);

                alert($xml.find('sheet').length);

                $xml.find('sheet').each(function ()
                {
                    alert("here2");
                    var sheet = $(this);
                    var menuName = $(sheet).attr("name");
                    alert(menuName);
                });
            }
        });

Upvotes: 1

Related Questions