0

我正在使用NSXmlParser并尝试解析这个 XML 文件:

<api>
<query>
<normalized>
<n from="new york" to="New york"/>
</normalized>
<redirects>
<r from="New york" to="New York"/>
</redirects>
<pages>
<page pageid="8210131" ns="0" title="New York">
<extract xml:space="preserve">&lt;p>&lt;b>New York&lt; ...

基本上这个文件很长,但我试图只复制<extract>元素。

NSMutableString用这段代码通过几种方式完成了它:

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    CrrentString = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [CrrentString appendString:string];
    NSLog(@"%@",CrrentString);
}

-(void)parser:(NSXMLParser *)parser
   didStartElement:(NSString *)elementName
   namespaceURI:(NSString *)namespaceURI
  qualifiedName:(NSString *)qName
     attributes:(NSDictionary *)attributeDict
{
    currentKey = nil;

    if ([elementName isEqualToString:@"extract"]) {
        CrrentString = [attributeDict objectForKey:@"extract"];
        return;
    }
}

但最后,这只给了我( )>内部。NSMutableStringCrrentString

4

1 回答 1

2

这一行提出了问题:

CrrentString = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

每次找到的字符方法起作用时,它都会覆盖以前的CrrentString. 这就是为什么你只得到最后一个找到的字符。

所以改变它:

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSString *temp= (NSString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [CrrentString appendString:temp];
    NSLog(@"%@",CrrentString);
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    CrrentString = nil;

    if ([elementName isEqualToString:@"extract"])
    {
        CrrentString = [[NSMutableString alloc] init];
    }
}

希望它会有所帮助。

于 2012-09-13T17:14:00.463 回答