【问题标题】:Can't find node of imported xml file找不到导入的xml文件的节点
【发布时间】:2016-04-13 10:04:54
【问题描述】:

导入 XML 文件后,我试图获取“工作表”节点的长度,但当它们应该有 3 个时,它们返回为 0。任何帮助使其工作的帮助将不胜感激。谢谢。

 $(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);
                    });
                }
            });

这是 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>

【问题讨论】:

    标签: jquery html ajax xml


    【解决方案1】:

    由于 DataType 设置为 xml,xml2 变量已被解析。 因此,删除 xmlDoc 步骤。 以下代码有效:

    $.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);
                    });
                }
            });
    

    【讨论】:

    • 效果很好。谢谢!
    • 如果有帮助请accept这个答案。谢谢。
    猜你喜欢
    • 2018-03-12
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多