How to parse xml attributes in objective-c?

2019-08-03 16:46发布

问题:

My xml is like this:

<Schedule id="1296" date="2010-05-20">
−
<Sports>
<Sport id="1" name="Football" abbr="FB"/>
<Sport id="2" name="Basketball" abbr="BK"/>
<Sport id="3" name="Baseball" abbr="BB"/>
<Sport id="4" name="Hockey" abbr="HK"/>
<Sport id="5" name="Other" abbr="OT"/>
</Sports>
−
<Leagues>
<League id="1" league_id="1" sport_id="1" periods="4" half_time_minutes="12" name="NFL" abbr="NFL" covers_league="NFL" covers_sport="football"/>
<League id="2" league_id="2" sport_id="1" periods="4" half_time_minutes="18" name="College Football" abbr="CFB" covers_league="NCAAF" covers_sport="football"/>
<League id="3" league_id="3" sport_id="2" periods="4" half_time_minutes="15" name="NBA" abbr="NBA" covers_league="NBA" covers_sport="basketball"/>
<League id="4" league_id="4" sport_id="2" periods="2" half_time_minutes="15" name="College Basketball" abbr="CBK" covers_league="NCAAB" covers_sport="basketball"/>
<League id="5" league_id="5" sport_id="3" periods="9" half_time_minutes="0" name="MLB" abbr="MLB" covers_league="MLB" covers_sport="baseball" ml="true"/>
<League id="6" league_id="6" sport_id="3" periods="9" half_time_minutes="0" name="College Baseball" abbr="CBB" ml="true"/>
<League id="7" league_id="7" sport_id="4" periods="3" half_time_minutes="0" name="NHL" abbr="NHL" covers_league="NHL" covers_sport="hockey" ml="true"/>
<League id="8" league_id="8" sport_id="2" periods="4" half_time_minutes="15" name="WNBA" abbr="WNBA" covers_league="WNBA" covers_sport="basketball"/>
</Leagues>

how can i parse the values in this xml?

回答1:

Use NSXMLParser.. Try following this tutorial:

programming guide on NSXMLParser



回答2:

to get to the attribute you first have to tell the compiler which element you want to take the attribute(s) from. So I would use an if statement. Lets say we want to get the "name" attribute value. It is inside the Sport element. So we would write.

if([elementname isEqualToString:@"Sport"]){
   nameString = [attributeDict objectForKey:@"name"];
}

it will look for the element Sport and then store the value of that elements attribute called name into an NSString we have names nameString.



回答3:

You have to use NSXMLParser.