使用jquery迭代xml并显示每个父节点的子节点

时间:2011-09-15 07:46:49

标签: javascript jquery xml

请帮助。谷歌搜索和堆栈溢出这几天,所以请听我说。

我有一个xml文件:

 <Sports>
       <MasterEvents MasterName="KungFu" Time="15 Sept 2011">
          <Event EventID="1" EventName="Event1">
             <Competitor CompetitorName="New Zealand" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
          </Event>
       </MasterEvents> 

       <MasterEvents MasterName="Karate" Time="15 Sept 2011">
          <Event EventID="1" EventName="Karate Event1">
             <Competitor CompetitorName="New Zealand" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
          </Event>

          <Event EventID="2" EventName="Karate Event2">
             <Competitor CompetitorName="New Zealand" BetID="2">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
          </Event>

          <Event EventID="3" EventName="Karate Event3">
             <Competitor CompetitorName="New Zealand" BetID="3">
                <BetType BetTypeName="Curved" Price="1.00" />
             </Competitor>
          </Event>
       </MasterEvents> 

       <MasterEvents MasterName="Judo" Time="15 Sept 2011">
          <Event EventID="1" EventName="Event1">
             <Competitor CompetitorName="Brazil" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
             <Competitor CompetitorName="Fiji" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
             <Competitor CompetitorName="US" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
             <Competitor CompetitorName="Alabama" BetID="1">
                <BetType BetTypeName="Straight" Price="1.00" />
             </Competitor>
          </Event>
       </MasterEvents> 
    </Sports>

我想要实现的是将所有MasterEvent放入下拉列表中,当我从下拉列表中选择一个MasterEvent时,会出现一个新的下拉列表,其中列出与所选MasterEvents相关的所有事件,然后列出竞争对手将出现(CompetitorName,Bettype,Price)。

这对我来说相当复杂,因为我刚刚开始使用XML和JQuery。如果你们可以摆脱一些灯光,请欣赏。

感谢。

1 个答案:

答案 0 :(得分:0)

不是完整的工作示例,但你可以得到这个想法

  $("#btn").click(function(){     
        xmlDoc = $.parseXML(xml),
        $xml = $(xmlDoc);        


        $($xml).find("Sports").each(function(index,j){
            $(this).find("MasterEvents").each(function(i,j){
        var txt = $(this).attr("MasterName");
      $("<option/>").text(txt).appendTo("select");
            });    

        });
    });

这里是小提琴http://jsfiddle.net/BajVk/1/