1

I have the following very simple XML returned from a webserver which I use ASIHttpRequest to connect to:

<element1>something</element1>
<element2>somethingelse</element2>
<element3>anotherthing</element3>

ASIHttpRequest can return it as NSData or NSString. I need to parse the information, what is the easiest way to do so?

Thanks

epetousis
  • 455
  • 1
  • 4
  • 21
derpking
  • 55
  • 1
  • 3
  • http://stackoverflow.com/search?q=objective-c+parse+xml – vikingosegundo Sep 07 '11 at 02:09
  • possible duplicate of [Parsing XML in Cocoa](http://stackoverflow.com/questions/1089737/parsing-xml-in-cocoa) – vikingosegundo Sep 07 '11 at 02:11
  • possible duplicate of [Cocoa/Objective-C : Best Practice to parse XML Document?](http://stackoverflow.com/questions/2237757/cocoa-objective-c-best-practice-to-parse-xml-document) – jscs Sep 07 '11 at 02:28

2 Answers2

7

There are some XML parsers available for iOS NSXMLParser, libxml2 (DOM and SAX),TBXML,KissXML. You can refer http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project to choose best XML Parser (Speed and memory footprint). Easiest would be TBXML. NSXMLParser is easy as well.

NSXMLParser* xmlParser = [[NSXMLParser alloc] initWithData:receivedXMLData];//init NSXMLParser with receivedXMLData
[xmlParser setDelegate:self]; // Set delegate for NSXMLParser
[xmlParser parse]; //Start parsing
[xmlParser release];

//Delegate Methods
//Have a instance variable NSMutableString* currentString; to hold data between elements and NSMutableArray* elementsArray; to hold parsed data

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    elementsArray = [[NSMutableArray alloc] init];
}

//store all found characters between elements in currentString mutable string
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if(!currentString)
    {
        currentString = [[NSMutableString alloc] init];
    }
    [currentString appendString:string];    
}

//When end of XML tag is found this method gets notified
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"element1"])
    {
        [elementsArray addObject:currentString];
        [currentString release],currentString=nil;
        return;
    }
    if([elementName isEqualToString:@"element2"])
    {
        [elementsArray addObject:currentString];
        [currentString release],currentString=nil;
        return;
    }
    if([elementName isEqualToString:@"element3"])
    {
        [elementsArray addObject:currentString];
        [currentString release],currentString=nil;
        return;
    }
    [currentString release],currentString =nil;
}

//Parsing has ended
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"Content of Elements Array: %@",elementsArray);
        [elementsArray release],elementsArray=nil;
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    UIAlertView* parseErrorAlert = [[UIAlertView alloc] initWithTitle:@"Parse Error" message:[NString stringWithFormat:"%@",[parseError localizedDescription]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [parseErrorAlert show];
    [parseErrorAlert release];
}

You have other delegate methods too like parseErrorOccured. Refer http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html

For TBXML : http://tbxml.co.uk/TBXML/API.html Updated: Implemented parseError delegate method and valid xml example XML You posted in code is not a valid XML (You can check XML validation online: http://validator.w3.org/#validate_by_input) so it will throw an parseError. Here is valid XML for XML you posted in question:

<?xml version="1.0"?>
<root>
 <element1>something</element1>
 <element2>somethingelse</element2>
 <element3>anotherthing</element3>
</root>
0x8badf00d
  • 6,391
  • 3
  • 35
  • 68
  • Thank you, that code is great, but it only seems to store element1 for some reason. – derpking Sep 07 '11 at 10:03
  • Because the XML Validation failed on line 2. If you implement parseErrorOccured delegate method it will throw NSError object with localized description,error code. Here is properly formatted xml something somethingelse anotherthing – 0x8badf00d Sep 07 '11 at 10:13
  • Thanks, I will have to append these to the string as the api I am working with just gives what I said in my original question. Thanks for helping – derpking Sep 07 '11 at 14:11
  • Got it working nicely, built up an nsmutablestring with the correct xml format and the elements from the api request, converted it into an nsdata and passed it to the parser. Thanks so much – derpking Sep 07 '11 at 14:20
0

Try also XMLObject. This may helps if you want to keep your cocoa style in your project.

Petr Syrov
  • 14,689
  • 3
  • 20
  • 30