Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse an NSString containing XML in Objective-C?

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?

like image 263
Raju Avatar asked May 29 '09 04:05

Raju


2 Answers

Download: https://github.com/bcaccinolo/XML-to-NSDictionary

Then you simply do :

NSDictionary *dic = [XMLReader dictionaryForXMLString:myxml error:nil];

Result is a NSDictionary *dic with dictionaries, arrays and strings inside, depending of the XML:

{
    students =     {
        student =         {
            address = abcd;
            age = 25;
            name = Raju;
        };
    };
}
like image 71
Cœur Avatar answered Nov 07 '22 20:11

Cœur


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_Class/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);
}
like image 45
Jon Hess Avatar answered Nov 07 '22 21:11

Jon Hess