我正在使用NSXMLParser
解析以下XML,但是只想根据XML中找到的唯一元素解析某些元素和属性,然后中止解析。
例如,我的XML看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<systems>
<system id="system1">
<game title="game1">
<checksums>
<checksum value="checksumvalue1" />
</checksums>
<players>
<player name="name1" description="description1" />
<player name="name2" description="description2" />
</players>
</game>
</system>
我希望能够仅根据players
的值返回game
中的所有checksum
因此,如果我将checksumvalue1
传递给我的方法,我只想使用唯一校验和返回在该players
个节点中找到的game
。在XML中,将会有其他带校验和的游戏,但校验和将始终是唯一的。
到目前为止,我有一些基本的解析器代码来从校验和值中读取元素和属性,但我不知道从那里去哪里。我也想知道使用XPath NSXMLNode
是否更有意义来实现这一目标。
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"checksum"] && [[attributeDict valueForKey:@"value"] isEqualToString:@"checksumvalue1"]) {
NSString *checksumValue = [attributeDict valueForKey:@"value"];
NSLog(@"value: %@", checksumValue);
// print players in only one game node that contains the unique checksum value
}
}
感谢您的帮助!
答案 0 :(得分:0)
您必须跟踪您是否已找到校验和以及您遇到的所有玩家。您需要布尔值foundGameChecksum
和NSMutableArray* players
。不要忘记players = [[NSMutableArray alloc] init];
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"checksum"] && [[attributeDict valueForKey:@"value"] isEqualToString:@"checksumvalue1"]) {
NSString *checksumValue = [attributeDict valueForKey:@"value"];
NSLog(@"value: %@", checksumValue);
foundGameChecksum = YES;
// print players in only one game node that contains the unique checksum value
} else if(foundGameChecksum && [elementName isEqualToString:@"player"]) {
[players addObject:[attributeDict valueForKey:@"name"]];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if(foundGameChecksum && [elementName isEqualToString:@"players"]) {
[parser abortParsing]; // Stop parsing
}
}
然后在[parser parse];
执行后,您将拥有players
即:
<?xml version="1.0" encoding="UTF-8"?>
<systems>
<system id="system1">
<game title="game1">
<checksums>
<checksum value="checksumvalue1" /> <!-- Found. Start adding -->
</checksums>
<players>
<player name="name1" description="description1" /> <!-- Add -->
<player name="name2" description="description2" /> <!-- Add -->
</players> <!-- Stop adding -->
</game>
</system>
</systems>