2010-12-11 57 views
1

我仍然在解析一个XML文件时环顾我的脑海。目前我正在使用TBXML从XML文件获取信息。在XML中访问子项?

以下是我从不同的XML文件中得到了一些数据:

TBXML  *XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:locationString]] retain]; 
TBXMLElement *rootXML = XML.rootXMLElement; 
TBXMLElement *e = [TBXML childElementNamed:@"Result" parentElement:rootXML]; 
TBXMLElement *WOEID = [TBXML childElementNamed:@"woeid" parentElement:e]; 
NSString  *woeid = [TBXML textForElement:WOEID]; 

它工作的罚款。

但是,现在我想从这个例子中获取雅虎RSS XML文件的温度。

http://weather.yahooapis.com/forecastrss?w=12700023

我不知道如何访问一个包含天气行。我如何使用TBXML来做到这一点?

谢谢!

回答

3

由于TBXML只允许您访问子项,您必须走树才能找到您想要的元素,基本上就像您在示例代码中那样。一般来说,如果有多个具有给定节点名称的子节点,则需要循环。如果您只需要第一个,则可以使用if-else语句而不是循环。

TBXML  *XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:locationString]] retain]; 
TBXMLElement *rss = XML.rootXMLElement, 
      *channel, 
      *units, 
      *item, 
      *condition; 
NSString  *temperatureUnits, 
      *temperature; 

for (channel = [TBXML childElementNamed:@"channel" parentElement:rss]; 
    channel; 
    channel = [TBXML nextSiblingNamed:@"channel" searchFromElement:channel]) 
{ 
    for (units = [TBXML childElementNamed:@"units" parentElement:channel]; 
     units; 
     units = [TBXML nextSiblingNamed:@"units" searchFromElement:units]) 
    { 
     if ((temperatureUnits = [TBXML valueOfAttributeNamed:@"temperature" forElement:units])) { 
      [temperatureUnits retain]; 
      break; 
     } 
    } 
    for (item = [TBXML childElementNamed:@"item" parentElement:channel]; 
     item; 
     item = [TBXML nextSiblingNamed:@"item" searchFromElement:item]) 
    { 
     for (condition = [TBXML childElementNamed:@"yweather:condition" parentElement:item]; 
      condition; 
      condition = [TBXML nextSiblingNamed:@"yweather:condition" searchFromElement:condition]) 
     { 
      temperature = [TBXML valueOfAttributeNamed:@"temp" forElement:condition]; 
      // do something with the temperature 
     } 
    } 
    [temperatureUnits release]; 
    temperatureUnits = nil; 
} 

如果你不想来处理回路的温度,将它们添加到某种类型的集合(可能是一个NSMutableArray)。

+0

它的工作原理,虽然调用'[温度单位发布];'它崩溃的应用程序。也许它是零。我开始认为使用TBXML是一个坏主意,我应该坚持使用默认的NSXML吗? – 2010-12-12 05:30:41

+1

实际上,这是因为'temperatureUnits' *不是*零(零忽略消息)。已经很晚了,我把自己搞糊涂了,认为“温度单位”正在循环。 “温度单位”的“保留”/“释放”并不是严格意义上的必要。原本,我正朝着另一个方向前进。通过将'temperatureUnits'设置为释放后(如更新后的答案)或删除'retain'&'release'来修复它。 – outis 2010-12-12 11:36:03

+0

我会用'NSXML',因为它支持[XPath和XQuery](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/NSXML_Concepts/Articles/QueryingXML.html#//apple_ref/doc/uid/TP40001258-CJBFCGEG),所以你可以直接访问你想要的节点。 – outis 2010-12-12 11:39:23