2010-04-19 65 views
0

我已经看过一些在网络上的例子,但我仍然在为此而苦苦挣扎。 我想获得的“indexDesc”标签内,然后,显示从“最后”标签后的值“descShort”标签的价值?我见过使用箭头的人>但我仍然迷路。从jQuery获取嵌套的XML项目

<indices> 
    <index> 
     <code>DJI</code> 
     <exchange>NYSE</exchange> 
     <liveness>DELAYED</liveness> 
     <indexDesc> 
      <desc>Dow Jones Industrials</desc> 
      <descAbbrev>DOW JONES</descAbbrev> 
      <descShort>DOW JONES</descShort> 
      <firstActive></firstActive> 
      <lastActive></lastActive> 
     </indexDesc> 
     <indexQuote> 
      <capital> 
       <first>11144.57</first> 
       <high>11153.79</high> 
       <low>10973.92</low> 
       <last>11018.66</last> 
       <change>-125.9</change> 
       <pctChange>-1.1%</pctChange> 
      </capital> 
      <gross> 
       <first>11144.57</first> 
       <high>11153.79</high> 
       <low>10973.92</low> 
       <last>11018.66</last> 
       <change>-125.9</change> 
       <pctChange>-1.1%</pctChange> 
      </gross> 
      <totalEvents>4</totalEvents> 
      <lastChanged>16-Apr-2010 16:03:00</lastChanged> 
     </indexQuote> 
    </index> 
    <index> 
     <code>XAO</code> 
     <exchange>ASX</exchange> 
     <liveness>DELAYED</liveness> 
     <indexDesc> 
      <desc>ASX All Ordinaries</desc> 
      <descAbbrev>All Ordinaries</descAbbrev> 
      <descShort>ALL ORDS</descShort> 
      <firstActive>06-Mar-1970</firstActive> 
      <lastActive></lastActive> 
     </indexDesc> 
     <indexQuote> 
      <capital> 
       <first>5007.30</first> 
       <high>5007.30</high> 
       <low>4934.00</low> 
       <last>4939.40</last> 
       <change>-67.9</change> 
       <pctChange>-1.4%</pctChange> 
      </capital> 
      <gross> 
       <first>5007.30</first> 
       <high>5007.30</high> 
       <low>4934.00</low> 
       <last>4939.40</last> 
       <change>-67.9</change> 
       <pctChange>-1.4%</pctChange> 
      </gross> 
      <totalEvents>997</totalEvents> 
      <lastChanged>19-Apr-2010 17:02:54</lastChanged> 
     </indexQuote> 
    </index> 
</indices> 
+0

你必须更好地描述它。有多个'last'标签,你想如何输出?你能提供一个例子吗? – 2010-04-19 17:46:41

+0

对不起,我只想从“gross”父标记中获得“last”值以及之前的shortDesc – Dkong 2010-04-19 18:58:34

回答

1

“>”是选择器;你可以在这里看到所有可用的:selectors。 “div> span”会找到所有以div作为父母的跨度。这与“div span”不同,它可以找到div的所有后缀。

var values = []; 

$(yourXml).find('index').each(function() { 
    var self = $(this); 

    values.push({ 
    descShort: self.find('descShort:first').text(), 
    capitalLast: self.children('capital').children('last').text(), 
    grossLast: self.children('gross').children('last').text() 
    }); 
}); 

values现在是对象的数组,每个descShort,captialLast和grossLast性质。

不幸的是我无法测试我的代码。

+0

感谢您的回答。由于某些原因,这些值将变空。当我打印这个值时,它总是说'未定义'。即 alert(self.find('descShort:first')。val()); – Dkong 2010-04-19 19:16:51

+0

尝试使用.text()或.html()代替。不知道为什么我第一次使用.val()tbh :) – Matt 2010-04-20 09:43:44

+0

@Matt:您可以编辑您的答案并修复此问题;) – 2010-04-20 11:22:29