I'm a n00b to iPhone programming and found it a real PITA to get an XML parser working. After piecing together things from various Google searches, here's what I got to work:
Code:
#import <Foundation/Foundation.h>
#import <Foundation/NSXMLParser.h>
- (void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"found file and started parsing");
}
- (void)parseXMLFileAtURL:(NSString *)URL //URL is the file path (i.e. /Applications/MyExample.app/MyFile.xml)
{
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL fileURLWithPath:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
NSXMLParser *parser = [[ NSClassFromString(@"NSXMLParser") alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[parser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"found this element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
}
Some other key points:
- having a bad XML file will also cause your parser to not work. This means unclosed tags, or not having the xml declaration at the top, like: "<?xml version="1.0" encoding="UTF-8"?>"
- also, you need to include some other stuff when you compile. Otherwise it will compile just fine, but won't parse anything. This is my include list: "-lobjc -framework CoreFoundation -framework Foundation -framework UIKit -framework CoreGraphics -framework GraphicsServices -framework IOKit -framework WebKit -framework LayerKit -framework OfficeImport" IOKit through OfficeImport seem to be necessary. I tried to leave one out and it just doesn't work
- finally, I'm doing all of this with the toolchain, so things might be different with the genuine SDK, but this works for me.
Good luck!