Accessing child in XML?
I'm still wrapping my head around parsing an XML file. Currently I'm using TBXML to get info from a XML file.
Here's how I got some data from a different XML file:
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];
It work's fine.
However, now I'm wanting to get the temperature from this example Yahoo RSS XML file.
http://weather.yahooapis.com/forecastrss?w=12700023
I don't know how开发者_开发知识库 to access the line that contains the weather. How can I do this using TBXML?
Thanks!
Since TBXML only lets you access children, you'll have to walk the tree to find the element(s) you want, basically as you do in your sample code. Generally speaking, you'll need to loop, in case there are multiple children with a given node name. If you only need the first, you can use an if-else statement instead of a loop.
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;
}
If you don't want to process the temperatures in the loop, add them to a collection of some sort (probably an NSMutableArray).
精彩评论