【问题标题】:How to parse xml data received as response text from jquery如何解析从jquery作为响应文本接收的xml数据
【发布时间】:2014-05-29 17:51:48
【问题描述】:

我有一个网络服务调用。它以加密格式发送响应作为响应文本。当我解密响应文本时,我会得到一个 XML 数据。现在我想解析这个 xml 数据。哪位大神可以给个思路

var respon = decrypted.toString(CryptoJS.enc.Utf8);

alert(respon);

var xml = jQuery(respon);
alert(xml.find('line:first').text());

【问题讨论】:

    标签: javascript jquery web-services parsing xml-parsing


    【解决方案1】:

    将您的响应 xml 放入 $ 函数中。就像假设你得到了:

    var str = '<NewDataSet> <Table> <line>1</line> <Trimestre>Octubre-Diciembre</Trimestre> <currency>EU?</currency> <growth>6.7</growth> <balanced>4.73</balanced> <moderate>2.98</moderate> </Table> <Table> <line>1</line> <Trimestre>Octubre-Diciembre</Trimestre> <currency>US$</currency> <growth>10.76</growth> <balanced>7.57</balanced> <moderate>5.44</moderate> </Table> </NewDataSet> ';
    
    var xml = jQuery(str);
    console.log(xml.find('line:first').text())
    

    使用调试器或 console.log 进一步迭代您的 $(xml)

    【讨论】:

    • 我得到的响应是 responseText 而不是 responseXml
    • 是的,无论您得到什么,您都必须将该 xml 字符串包含在 $ 函数中。使用$(responseText) 开始解析。供参考,您可以使用此链接:think2loud.com/224-reading-xml-with-jquery
    • 1Octubre-DiciembreEU?6.74.73 2.98
      1Octubre-DiciembreUS$10.76 7.575.44
      这是从 responseText 获得的 xml。当我解密响应文本时
    • 查看更新后的答案。我刚刚写了一种方法,以便您可以访问line 节点并打印其内部文本。
    • 它正在工作。我首先在我这边进行了测试,然后才更新了答案。你遇到了什么错误?
    【解决方案2】:

    我不确定“解析”的确切含义。但是,如果“解析”意味着从某个 xml 中获取多个数据,那么下面的代码会有所帮助。

    var data = [];
    
    $.ajax({
        url: "some-url/sample.xml",
            async: true,
            cache: true,
            dataType:"xml",
            success: function(xml){
                $(xml).find('item').each(function(i){
                    data.push({
                        'id': $(this).find("id").text(),
                        'title'    : $(this).find("title").text()
                    });
                });
        },
        error: function(err){
            console.log(err);
        }
    });    
    

    示例.xml

    <item>
    <id>1</id>
    <title>Alasteir</title>
    </item>
    <item>
    <id>2</id>
    <title>Bob</title>
    </item>
    <item>
    <id>3</id>
    <title>John</title>
    </item>
    <item>
    <id>4</id>
    <title>Mary</title>
    </item>
    <item>
    <id>5</id>
    <title>Tom</title>
    </item>
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2016-11-03
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多