2011-06-13 215 views
5

如何使用NSXML解析器從XML中提取屬性?NSXMLParser解析屬性

繼承人我的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。

感謝

回答

15
if([elementName isEqualToString:@"enclosure"]) 
{ 
    NSString *urlValue=[attributeDict valueForKey:@"url"]; 
    NSString *urlValue=[attributeDict valueForKey:@"type"]; 
    NSString *urlValue=[attributeDict valueForKey:@"length"]; 
} 
+1

+1 ...簡單ñ好的答案.. :)) – mAc 2011-12-13 09:58:32

+1

雅它的很酷的答案.. – 2013-01-28 11:17:59

+0

謝謝你的答案。 我想補充說,這些行應該到'NSXMLParser'的代理方法,它是: ' - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName屬性:(NSDictionary *)attributeDict'。 – Neeku 2013-11-11 15:05:30

1

的方法...

(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qualifiedName 
    attributes:(NSDictionary *)attributeDict 

給你屬性的字典和他們的鑰匙(attributeDict)...找鍵入「URL」的條目時elementName爲等於「圈地」 ......

3

你需要使用的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"]; 

    } 
0

下面是解釋: 示例XML具有屬性:

enter image description here

使用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]; 
    } 
}