2011-12-02 132 views
3

我真的很陌生,我试图阅读RSS提要,到目前为止一切都很好。我这样做:iOS:NSXMLParser获取属性

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
    if ([elementName isEqualToString:@"item"]) { 
    [item setObject:currentTitle forKey:@"title"]; 
    [item setObject:currentLink forKey:@"link"]; 
    [item setObject:currentSummary forKey:@"summary"]; 
    [item setObject:currentDate forKey:@"date"]; 
    [item setObject:currentImage forKey:@"enclosure"]; 

    [stories addObject:[item copy]]; 
    NSLog(@"adding story: %@", currentTitle); 
    } 
} 

问题是外壳。它看起来像这样的XML:

<enclosure length="150" url="urltoimage.jpg" type="image/jpeg" /> 

如何获得网址从元素属性从我的函数内?

编辑的XML看起来是这样的:

<item> 
    <title>...</title> 
    <link>...</link> 
    <description>...</description> 
    <pubDate>...</pubDate> 
    <enclosure length="150" url="urltoimage.jpg" type="image/jpeg" /> 
</item> 

而且我foundCharacters功能如下:

- (void)parser: (NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if ([currentElement isEqualToString:@"title"]) { 
    [currentTitle appendString:string]; 
    } else if ([currentElement isEqualToString:@"link"]) { 
    [currentLink appendString:string]; 
    } else if ([currentElement isEqualToString:@"description"]) { 
    [currentSummary appendString:string]; 
    } else if ([currentElement isEqualToString:@"pubDate"]) { 
    [currentDate appendString:string]; 
    } 
} 
+0

http://stackoverflow.com/questions/6081629/parsing-xml-file-with-nsxmlparser-getting-values – Tendulkar

回答

12
- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qualifiedName 
    attributes:(NSDictionary *)attributeDict 
{ 
    // just do this for item elements 
    if(![elementName isEqual:@"enclosure"]) 
     return; 

    // then you just need to grab each of your attributes 
    NSString * name = [attributeDict objectForKey:@"url"]; 

    // ... get the other attributes 

    // when we have our various attributes, you can add them to your arrays 
    [m_NameArray addObject:name]; 

    // ... same for the other arrays 
} 
+0

我的问题已更新,可能会改变很多? – tbleckert

+0

没有工作完美! – tbleckert

6

你必须处理一个更加回调跟踪属性:

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

attributeDict is dic tionary所有找到的元素参数

+0

啊,亲爱的谢谢!太糟糕了,你不能接受两个答案... + 1无论如何! – tbleckert