UPDATE: I decided to change my web service to output JSON, much easier to work with. I'll leave this open incase anyone can come up with a sensible solution, and in case it helps others.
I'm grabbing an XML file, parsing it, and trying to get content from specific tags:
//Grab the hosted XML
NSError *error;
NSURL *mainContentURL = [NSURL URLWithString:@"http://www.andrewlarking.co.uk/DigiCons/appContent.xml"];
NSString *mainPageContents = [NSString stringWithContentsOfURL:mainContentURL encoding:NSUTF8StringEncoding error:&error];
NSData *mainPageData = [mainPageContents dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"mainPageData returned = %@", [[NSString alloc] initWithData:mainPageData encoding:NSUTF8StringEncoding]);
//Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:mainPageData];
[parser setDelegate:self];
[parser parse];
}
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"In parser");
if([elementName isEqualToString:@"feb5Content"])
{
NSLog(@"In elementname");
NSLog(@"valueforkey title = %@", [attributeDict valueForKey:@"page.title"]);
self.dcViewControllerLabel.text = [attributeDict valueForKey:@"page.title"];
}
}
All is good, but the value for key@"page.title" or @"title" returns null. Here is the XML:
<feb5Content>
<page>
<title>I am a test title.</title>
<subTitle>I am the subtitle.</subTitle>
</page>
</feb5Content>
Any thoughts?
Ideally I'd like to be able to grab the content of various elements that exist within the element. So I could have title, subTitle, bodyText all under and I'd need to grab those. Each page of the app will have it's contents stored in a element.
Cheers.
That's because your page title is not an attribute of the
<feb5Content>
element. It is the value of the<title>
element. So you have to listen to the start of the<title>
element:And then in the following method get the value inside the
<title>
element:This method is called everytime that text is found inside an XML element. So you have to check if you are inside the
<title>
element when this method is called. That's why I included the ivarself.isTitleElement
.To store the page titles you can put them into an NSMutableArray ivar.