【问题标题】:Get XML data - Jquery - Filter获取 XML 数据 - Jquery - 过滤器
【发布时间】:2017-12-04 08:57:54
【问题描述】:

我正在尝试使用 jquery 过滤功能并解析 XML,但遇到了问题。 我的 XML 如下所示:

<root>
    <data name="0121C395-AFCE-49C8-A163-55E24325D691" xml:space="preserve">
        <value>Report an incident</value>
    </data>
    <data name="0121C395-AFCE-49C8-A163-55E24325D691_descr" xml:space="preserve">
        <value>In this service it's possible to report incidents.</value>
    </data>
    <data name="0121C395-AFCE-49C8-A163-55E24325D691_short" xml:space="preserve">
        <value>Report Incident</value>
    </data>
</root>

我的 Jquery 看起来像这样:

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "http://localhost/servicemarket/ReachOut/Services.xml",
        dataType: "xml",
        success: function(xml){
            var dataVal = $(xml).find('data').filter(function(){
                return $('data', this).attr('name') == '0121C395-AFCE-49C8-A163-55E24325D691';
            });
            dataVal.each(function(index, data){
                console.log($(data).find('value').text());
            });
        },
        error: function() {
            alert("An error occurred while processing XML file.");
        }
    });
});

我的目标是根据传入的数据属性获取节点值。 非常感谢所有帮助! :) 谢谢!!

【问题讨论】:

    标签: jquery xml filter


    【解决方案1】:

    您的代码应该稍作修改:

        $(document).ready(function(){
        $.ajax({
            type: "GET",
             url: "http://localhost/servicemarket/ReachOut/Services.xml"
            dataType: "xml",
            success: function(xml){
                var dataVal = $(xml).find('data').filter(function(){
    
                    return $(this).attr('name') == '0121C395-AFCE-49C8-A163-55E24325D691';
                });
                //console.log(dataVal);
                dataVal.each(function(index, data){
                    console.log($(data).find('value').text());
                });
            },
            error: function() {
                alert("An error occurred while processing XML file.");
            }
        });
    });
    

    所以,使用$(this) 获取当前(由 find() 找到)对象。您的 $('data', this) 返回了一个空对象,因为 data 内部不包含另一个数据标签(如果我理解错误的话)。

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多