views:

4418

answers:

4

In my iPhone application, I have the following NSString:

NSString *myxml=@"<students>
    <student><name>Raju</name><age>25</age><address>abcd</address> 
    </student></students>";

How would I parse the XML content of this string?

+4  A: 

You should use the NSXMLParser class

Here's a link to the documentation for that class: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser%5FClass/Reference/Reference.html

Your code should look something like this:

@implementation MyClass
- (void)startParsing {
    NSData *xmlData = (Get XML as NSData)
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    NSLog(@"Started %@", elementName);
}
Jon Hess
I find the xml parsers that come with the google client libraries is much easier to use : http://code.google.com/p/gdata-objectivec-client/
Naren
A: 

I found a combination of the example and great explanation here:

http://weblog.bignerdranch.com/?p=48

and the source code download here:

http://www.iphonesdkarticles.com/2008/11/parsing-xml-files.html

was enough to get me started using NSXMLParser for my own code.

nevan
+1  A: 

Another answer is: Don't use XML. Use a plist instead, which is written using XML but more easily parsable in Objective-C into distinct data types (NSArray for example has a method to convert a file or NSData plist into an NSArray).

Kendall Helmstetter Gelner
A: 

Try out WonderXML: http://bit.ly/9AItyf

Luke Du