NSXMLParser 解析属性
Posted
技术标签:
【中文标题】NSXMLParser 解析属性【英文标题】:NSXMLParser Parsing Attributes 【发布时间】:2011-06-13 10:17:41 【问题描述】:如何使用 NSXML 解析器从 XML 中提取属性?
这是我的 xml:
<item>
<title>Button hails 'amazing' win</title>
<description>Jenson Button hailed yesterday's crazy Canadian Grand Prix victory as the best of his Formula One career.
</description>
<link>http://www.skysports.com/story/0,19528,12433_6986809,00.html</link>
<guid isPermaLink="false">12433_6986809</guid>
<pubDate>Mon, 13 Jun 2011 06:21:00 GMT</pubDate>
<category>News Story</category>
<enclosure type="image/jpg" url="http://img.skysports.com/11/06/128x67/Canadian-GP-Jenson-Button-celebrates1_2609288.jpg" length="123456" />
</item>
我需要从附件标签中获取 url。
谢谢
【问题讨论】:
【参考方案1】:if([elementName isEqualToString:@"enclosure"])
NSString *urlValue=[attributeDict valueForKey:@"url"];
NSString *urlValue=[attributeDict valueForKey:@"type"];
NSString *urlValue=[attributeDict valueForKey:@"length"];
【讨论】:
感谢您的回答。我想补充一点,这些行应该转到NSXMLParser
的委托方法,即:- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
。
让我开心...太简单了..:)【参考方案2】:
你需要使用 NSXMLParser 及其委托函数
-
(BOOL) parse:(NSData *)xmlData
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
那么你需要使用这样的东西
if([elementName isEqualToString:@"enclosure"])
NSMutableDictionary *Dict=[NSMutableDictionary dictionary];
[Dict setObject:[attributeDict valueForKey:@"url"] forKey:@"url"];
[categoryDict setObject:[attributeDict valueForKey:@"type"] forKey:@"type"];
【讨论】:
【参考方案3】:方法...
(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
为您提供属性及其键的字典(attributeDict)...当 elementName 等于“enclosure”时,查找键为“url”的条目...
【讨论】:
【参考方案4】:解释如下: 带有属性的示例 xml:
使用xml委托方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
if ([elementName isEqualToString:@"remoteContent"])
NSString* href = [attributeDict objectForKey:@"href"];
NSLog(@"href %@",href);
[someArray addObject:href];
【讨论】:
以上是关于NSXMLParser 解析属性的主要内容,如果未能解决你的问题,请参考以下文章
iOS - OC - XML 解析 - NSXMLParser