使用链式查询从列表中进行选择

时间:2013-08-29 10:10:18

标签: javascript jquery xml

我正在尝试构建一个jquery来从XML文件中选择项目,而我似乎无法正确地将它们链接在一起。

我已经解析了一个XML文件并将其附加到我的DOM中,这是一个示例结构

<Products>
  <product1>
    <Description>Pound</Description>
    <ProductType>CUR</ProductType>
    <CurrencyCode>GBP</CurrencyCode>
    <Rate>1</Rate></ProductRate>
  </product1>
  <product2>
    <Description>Euro</Description>
    <ProductType>TCQ</ProductType>
    <CurrencyCode>Eur</CurrencyCode>
    <Rate>1.5</Rate></ProductRate>
  </product2>
</Products>

所以我要做的是指定我想从XML中获取哪些元素并显示。我可以从XML中选择所有项目,我可以获取特定元素,但是当我尝试获取所有位置时,例如(ProductType == "CUR")我无法选择代码和速率,然后添加到我的列表中。

var $xml = $(xml);
var $list = $('#list'); 
    $prodtype = $xml.find("ProductType");

    $prodtype.each(function() {
    if($(this).text() == "CUR"){ 
    $CurrencyCode = $xml.find("CurrencyCode");      
    $CurrencyCode.each(function() {
$( "#list" ).append("<li><a>" + $(this).text() + " </a></li>");
       });
    }
});

我认为我对如何选择和存储元素感到困惑。所以在psuedo代码中,我认为我想要做的是

for each element where producttype == cur
grab next 2 siblings and append to list

希望这很清楚?

4 个答案:

答案 0 :(得分:1)

您可能需要使用parent()方法上升一个级别,然后返回到子货币(如果适用,则为费率)。

$prodtype.each(function() {
    if($(this).text() == "CUR"){ 
      var $parent = $(this).parent();
      var $CurrencyCode = $parent.find("CurrencyCode");      
      $("#list").append("<li><a>" + $CurrencyCode.text() + " </a></li>");
    }
}

答案 1 :(得分:1)

var $xml = $(xml);
var $list = $('#list'); 

$prodtype = $xml.find("ProductType");

$prodtype.each(function() {
    var self = $(this);
    if( self.text() == "CUR") { 
        var 
            $CurrencyCode = self.next('CurrencyCode')
            $Rate         = $CurrencyCode.next('Rate')          
        ; 
        $( "#list" ).append("<li><a>" + $Rate.text()+$CurrencyCode.text() + " </a></li>");

    }
});

答案 2 :(得分:1)

试试这个 -

$prodtype.each(function() {
    if($(this).text() == "CUR"){ 
    $CurrencyCode = $(this).siblings().find("CurrencyCode");
    $( "#list" ).append("<li><a>" + $CurrencyCode.text() + " </a></li>");        
    }
});

有关.siblings()

的更多信息

答案 3 :(得分:0)

如果我正确理解您的问题,您可以使用map()的嵌套调用:

$xml.find("ProductType").map(function() {
    return $(this).nextAll().slice(0, 2).map(function() {
        return $("<li><a>" + $(this).text() + "</a></li>");
    });
}).appendTo("#list");

外部调用从<ProductType>元素投射下两个兄弟节点,内部调用从这些兄弟节点中的文本中投射新的列表项。在那里,您只需拨打一次appendTo()即可填充您的列表。