【问题标题】:jQuery : XML - Reading child nodes from a specific nodejQuery:XML - 从特定节点读取子节点
【发布时间】:2012-03-08 23:59:13
【问题描述】:

我有一个 xml 文件,我想在其中读取特定节点的子节点...下面是 XML 文件。

XML 文件结构:

<?xml version="1.0" encoding="ISO-8859-1"?>

<categories>
<category type='Type A'>
    <genre>1</genre>
    <genre>2</genre>
</category>
<category type='Type B'>
     <genre>3</genre>
     <genre>4</genre>
     <genre>5</genre>
</category>
<category type='Type C'>
    <genre>6</genre>
</category>
</categories>

我需要使用此 XML 的一个示例是类别类型 B 的所有流派。我怎样才能过滤掉所有其他类别,以便我可以做一个 .find("genre").each。 ... 并且只返回流派 3,4 和 5。

这是我使用的代码:

$.ajax({
        type: "GET",
        url: "myxml.xml",
        dataType: "xml",
        success: function(data){
            xml = data;
            });
        }
    });

    return {getXml : function() 
    { 
        if (xml) return xml;
    }};
})();

/* On Category Change */
$(".category").change(function(){
    var xml = xmlArtists.getXml();

    $(".genre").find("option").remove().end();

    var type = $(this).val();
    var typeGenres = $(xml).find("categories").filter(function(){
        return $(this).find("category").attr("type") == type;
    });

    typeGenres.find("genre").each(function(){
        var genre = $(this).text();
        $(".genre").append("<option value=" + genre + ">" + genre + "</option>");
    });
});

.category 是一个对象,当它发生变化时,代码应该触发......因为在其变化时填充另一个对象,但无论如何这对于这个问题并不重要......

提前致谢!!

【问题讨论】:

  • 刚刚发现它比我想象的要容易...代码如下: /* On Category Change */ $(".category").change(function(){ var xml = xmlArtists. getXml(); $(".genre").find("option").remove().end(); var type = $(this).val(); $(xml).find("category[type ='" + type + "']").find("genre").each(function(){ var Genre = $(this).text(); $(".genre").append(""); }); });

标签: javascript jquery xml


【解决方案1】:
$(xml).find('category[type="Type B"] > genre')

这将找到所有type"Type B"category 节点,并获取每个匹配类别的所有genre 子节点。

【讨论】:

  • 哈哈,我在你回复之前就发布了,但由于我的声誉,它没有让我这样做,所以我把它作为评论。这比我想象的要容易......无论如何都非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2013-10-22
相关资源
最近更新 更多