开发者

NSXMLParser problem

开发者 https://www.devze.com 2023-03-14 03:59 出处:网络
I have an xml file with some rows like this: <Country ID=\"\" Name=\"Italy\" /> <City ID=\"\" Name=\"Rome\" />

I have an xml file with some rows like this:

  <Country ID="" Name="Italy" />
  <City ID="" Name="Rome" />
  <Place ID="" Name="Colosseum">

but when I parse it the element Country or City or Place are empty (line break)

My code is:

    - (void)parser:(NSXMLParser *)parser foun开发者_开发百科dCharacters:(NSString *)string{
        if ([currentElement isEqual:@"Country"]) {
             NSLog(@"Country %@", string);
        }
    }

Any help is appreciated.

Thanks, Max


The values you see in your xml are the element attributes, not element data. So it wont show up in 'foundCharacters' method. You will have to fetch the attribute values from the attributes dictionary in 'didStartElement' method:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([currentElement isEqual:@"Country"]) {
         NSLog(@"Country %@", [attributeDict objectForKey:@"Name"]);
    }
}   


Use the parser method as below:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    if(currentKey){
        if(!currentStringValue){
            currentStringValue = [[NSMutableString alloc] initWithCapacity:200];
        }
        [currentStringValue appendString:string];
    }
}


    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
    {
        if ([currentElement isEqual:@"Country"]) {
             NSLog(@"Country %@", [attributeDict objectForKey:@"Name"]);
        }
    }   

Hope it will be helpful to you.

Let me know in case of any difficulty.

0

精彩评论

暂无评论...
验证码 换一张
取 消