1

我正在解析以下 XML,NSXMLParser但只想根据 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因此 如果我传递给我的方法,我只想返回在该节点中找到的具有唯一校验和的值。在 XML 中,会有其他带有校验和的游戏,但校验和始终是唯一的。gamechecksumchecksumvalue1playersgame

到目前为止,我有一些基本的解析器代码可以从校验和值中读取元素和属性,但我不知道从那里去哪里。我还想知道NSXMLNode使用 XPath 是否更有意义来实现这一点。

- (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
   }
}

谢谢你的帮助!

4

1 回答 1

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

IE:

<?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>
于 2013-02-25T07:52:05.957 回答