Question

I have this XML file:

<continents>
    <continent1 id="EUR" name="EUROPE"></continent1>
    <continent2 id="AME" name="AMERICA"></continent2>
</continents>

I tried make it with NSXMLParser, but I cannot show the results in the same time, I would try it with touchXML someone can help me? thanks.

Was it helpful?

Solution

"Europe" and "America" are attributes of your tags. Attributes defined as "name" in the tag. You really should get familiar with NSXMLParser and the event driven method in which it parses. Basically you create an NSObject subclass to be the delegate of the NSXMLParser and as it encounters elements it calls delegate methods on your custom object. And this very simple XML is a perfect example to learn. For example.

This code uses ARC.

SimpleExampleParse.h:

@interface SimpleExampleParse : NSObject <NSXMLParserDelegate>
@property (strong, nonatomic) NSMutableArray *continents;
-(id)initWithString:(NSString *)stringToParse;
@end

SimpleExampleParse.m:

#import "SimpleExampleParse.h"
@implementation SimpleExampleParse{
    NSXMLParser *myParser;
}
@synthesize continents;
-(id)initWithString:(NSString *)stringToParse{
    if ((self = [super init])){
        myParser = [[NSXMLParser alloc] initWithData:[stringToParse dataUsingEncoding:NSUTF8StringEncoding]];
        myParser.delegate = self;
        self.continents = [[NSMutableArray alloc] init];
        [myParser parse];
    }
    return self;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    // Check to see if this element has an attribute "name".
    NSString *name = [attributeDict objectForKey:@"name"];
    // If name is not nil add it to our Array
    if (name) [continents addObject:name];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    // We don't care your XML contains no content
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    // We don't care your XML contains no content
}
@end

This class is used like this:

NSString *stringToParse = @"<continents><continent1 id=\"EUR\" name=\"EUROPE\"></continent1><continent2 id=\"AME\" name=\"AMERICA\"></continent2></continents>";
SimpleExampleParse *parser = [[SimpleExampleParse alloc] initWithString:stringToParse];
NSLog(@"contenents %@",parser.continents);

The output from the log will be:

contenents (
    EUROPE,
    AMERICA
)

Please now that you have something working in front of you take the time to study it and examine how it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top