尽管我看过所有的tutos,但我仍然有一些难以理解如何使用NSXMLParser ......
我有以下XML文件,例如:
<rss>
<channel>
<title>The Title</title>
<link>A URL</link>
<language>English</language>
<item>
<name>John</name>
<title>John4034</title>
<city>LA</city>
<country>USA</country>
</item>
....
<item>
<name>Marc</name>
<title>Marc2942</title>
<city>London</city>
<country>England</country>
</item>
</channel>
</rss>
我的目标是在项目的NSMutableArray中存储所有项目。我的班级项目有4个NSString(名称,标题,城市,国家)。
这是我的XMLParser.m文件:
- (id) loadXMLbyURL : (NSString *) urlString
{
items = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"item"]) currentItem = [Item alloc];
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"name"]) [currentItem setName:currentNodeContent];
if([elementName isEqualToString:@"title"]) [currentItem setTitle:currentNodeContent];
if([elementName isEqualToString:@"city"]) [currentItem setCity:currentNodeContent];
if([elementName isEqualToString:@"country"]) [currentItem setCountry:currentNodeContent];
}
if([elementName isEqualToString:@"item"])
{
[self.items addObject:currentItem];
currentItem = nil;
currentNodeContent = nil;
}
}
但有了这一切,我有两个问题:
请帮忙!
答案 0 :(得分:0)
如果有人遇到同样的问题,我终于找到了解决办法。