【问题标题】:jQuery help - Parse XML into arrayjQuery 帮助 - 将 XML 解析为数组
【发布时间】:2012-09-10 10:56:57
【问题描述】:

我目前正在开发一个 HTML 游戏,用户可以通过该游戏将项目拖放到正确的类别中。类别及其项目在 XML 文档中定义。

我的 XML 格式:

<config>
<game>
    <title>Dementia</title>
        <cat>
            <catTitle>Mild</catTitle>
            <item>mild-1</item>
            <item>mild-2</item>
            <item>mild-3</item>
        </cat>
        <cat>
            <catTitle>Moderate</catTitle>
            <item>Moderate-1</item>
            <item>Moderate-2</item>
            <item>Moderate-3</item>
        </cat>
        <cat>
            <catTitle>Severe</catTitle>
            <item>Severe-1</item>
            <item>Severe-2</item>
        </cat>
</game>

我想使用 jQuery 将此 XML 文件解析为基于其类别的单独数组。

例如:

array1 = [mild-1,mild-2,mild-3]

array2 = [Moderate-1,Moderate-2,Moderate-3] 等...

这将允许我根据类别数组检查被删除项目的属性是否正确。

如果您对如何做到这一点有任何其他想法,请提出建议。

提前谢谢你。

【问题讨论】:

    标签: jquery xml arrays http parsing


    【解决方案1】:

    试试,像这样:

    $(document).ready(function() {
        var arr = [];
        $(xml).find("cat").each(function(idx, v) {
            arr[idx] = [];
            $(v).find("item").each(function( i , vi) {
                arr[idx].push( $(vi).text() );
            });             
        });
        console.log( arr );
    });
    

    将返回如下响应:

    [
        ["mild-1", "mild-2", "mild-3"]
    , 
        ["Moderate-1", "Moderate-2", "Moderate-3"]
    , 
        ["Severe-1", "Severe-2"]
    ]
    

    所以你可以访问单个数组,

    console.log( arr[0] ); //for first, and so on..
    

    【讨论】:

      【解决方案2】:

      试试这样:

      $("cat", xml).each(function () {
         $("item", this).toArray();
      });
      

      【讨论】:

        【解决方案3】:
        $($.parseXML(xml)).find("cat").each(function (idx, v) {
          arr[idx] = [];
          $(v).find("item").each(function (i, vi) {
             arr[idx].push($(vi).text()
          );
         });
        

        因为$(xml) 在 IE 中不起作用(请参阅此 jQuery.find() 在 IE 中不返回数据,但在 Firefox 和 Chrome 中可以)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-23
          • 2011-06-21
          • 1970-01-01
          相关资源
          最近更新 更多