Parsing data with NSXML in iOS - ios

I'm trying to parse data from a Wordpress RSS feed using NSXMLR. My problem is exporting my parsed data. So far I have,
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"item"]){
currentTitle = [[NSMutableString alloc] init];
item = [[NSMutableDictionary alloc] init];
}
}
this class
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]){
[item setObject:currentTitle forKey:#"title"];
}
[stories addObject:item];
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]){
[currentTitle appendString:string];
}
}
NSMutableArray *stories;
NSMutableDictionary *item;
So in ViewDidLoad implementation, I have
//declare the object of allocated variable
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"URL"]];// URL that given to parse.
//allocate memory for parser as well as
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];
//asking the xmlparser object to beggin with its parsing
[xmlParserObject parse];
NSLog(#"%#", [item objectForKey:#"title"]);
My problem is that I only print one object, I have multiples elements. How can I make it scan every single one of them and print them all.
Thanks in advance.

If I understand your code correctly, item holds the currently parsed item,
and the array stories holds all items.
So you have to allocate the stories array first:
stories = [[NSMutableArray alloc] init];
Then you do the parsing (but you should add an error check):
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"URL"]];
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];
if (![xmlParserObject parse]) {
// Parsing failed, report error...
}
And finally print the contents of the array:
for (NSDictionary *story in stories) {
NSLog(#"%#", [story objectForKey:#"title"]);
}
The didEndElement method probably should look like this:
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]){
[item setObject:currentTitle forKey:#"title"];
[stories addObject:item]; // <-- MOVED INTO THE IF-BLOCK
}
}

Related

Imagesarray double when i back from detailview

I parse xml images urls from tableview to detailview when xml format is like
so I wrote like this
In below code the some content so i wrote the code like this.
this is another type of tag so wrote code like
if ([elementObj isEqualToString:#"media:thumbnail"]) {
[Imagesarray addObject:attributeDict[#"url"]];
}
In foundcharactor i dont use this because i got the array here
[Imagesarray addObject:attributeDict[#"url"]];
When i didnot use this in didendelement method because it does not have the attributedstring
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
elementObj = elementName;
if ([elementObj isEqualToString:#"media:thumbnail"]) {
[Imagesarray addObject:attributeDict[#"url"]];
NSLog(#"%# it is images array",Imagesarray);
}
if ([elementObj isEqualToString:#"item"]) {
_item = [[NSMutableDictionary alloc] init];
titleObj = [[NSMutableString alloc] init];
pubdataObj= [[NSMutableString alloc] init];
DiscriptionObj=[[NSMutableString alloc]init];
}
}
When i click on back button of the detail view all the images add to the array again.How can i write code for this.
Please help me.
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([elementObj isEqualToString:#"title"]) {
[titleObj appendString:string];
}
else if ([elementObj isEqualToString:#"pubDate"]) {
[pubdataObj appendString:string];
}
else if ([elementObj isEqualToString:#"description"]){
[DiscriptionObj appendString:string];
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"item"]) {
[_item setObject:titleObj forKey:#"title"];
[_item setObject:pubdataObj forKey:#"pubDate"];
[_item setObject:DiscriptionObj forKey:#"description"];
[feedsArry addObject:_item];
[];
}
}
Try checking whether you are parsing the array from viewdidappear or viewwillappear method. if yes this method will be called whenever the view is opened. it would be better to move parsing to viewdidload which will be called only once when the view is loading.

How to read a xml file in iOS

I want to read a xml file within my iOS. Im reading it like this
NSURL *url = [[NSURL alloc] initWithString:urlString] ;
purchasedBookXMLParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
PurchasedBookXMLParser *bookParser = [[PurchasedBookXMLParser alloc] initPurchasedBookXMLParser];
[purchasedBookXMLParser setDelegate:bookParser];
BOOL success = [purchasedBookXMLParser parse];
But im getting success NO always. When I give the same url in browser I can see the xml data. What is the reason for this. How can I solve this. Please help me.
Thanks
Did u implement parser delegate method ??
In my project what i am doing is as below
NSURL *url = [NSURL URLWithString:#"https://api.sportsdatallc.org/nascar-p3/sc/2015/races/schedule.xml?api_key=wstdt33unpyk7sgpmjj5qver"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
After that parser delegate methods call i.e. as below
If u want data between "race" tag then [element isEqualToString:#"race"]
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSString *element;
element = elementName;
if ([element isEqualToString:#"race"])
{
item2=[[NSMutableDictionary alloc] init];
[item2 setObject:attributeDict forKey:#"race"];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
[self.tableview reloadData];
}

EXC_BAD_ACCESS for NSXMLParser code

I have written the below code to parse RSS feeds. but i keep getting EXC_BAD_ACCESS in foundCharacter method when it tries to compare element with #"title".Any idea where am i going wrong?
NSMutableDictionary * item;
NSMutableString * title;
NSMutableString * link;
NSString *element;
NSMutableArray *feeds;
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc]init];
title = [[NSMutableString alloc]init];
link = [[NSMutableString alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[feeds addObject:[item copy]];
NSLog(#"feeds :: %#",feeds);
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([element isEqualToString:#"title"]) {
[title appendString:string];`enter code here`
}else if ([element isEqualToString:#"link"]){
[link appendString:string];
}
}
I think the mistake is in this line:
element = elementName;
You have to init the variable element. So write this one:
element = [[NSString alloc] initWithString:elementName];
Then it should work.

xml parsing having multiple opening tags

I m getting response like this
<NewDataSet>
<Map>
<URL>
https://maps.google.co.in/maps?q=ABIL+House,+Ganeshkhind+Road,+Yashwant+nagar,+Pune,+Maharashtra&hl=en&sll=18.539118,73.834095&sspn=0.011169,0.021136&oq=ABIL+House&t=h&hnear=ABIL+House,+2,+Ganeshkhind+Rd,+Yashwant+nagar,+Pune,+Maharashtra+411007&z=16
</URL>
</Map>
</NewDataSet>
I have to parse url value to show in web view. How to parse xml file having two opening tags, this is my code:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Result"]) {
item = [[NSMutableDictionary alloc] init];
currentUser =[[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"Result"]) {
[item setObject:currentUser forKey:#"Result"];
// [item setObject:currentPassword forKey:#"Name"];
[users addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser )parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:#"Result"]) {
[currentUser appendString:string];
}
/* if ([currentElement isEqualToString:#"Name"])
{
[currentPassword appendString:string];
}
*/
}
- (void)viewDidLoad
{
users = [[NSMutableArray alloc] init];
NSURL *xmlURL = [NSURL URLWithString:#"http://abilcms.com.sv2.premiumwebserver.com/WebServiceStatus.aspx?UserID=demo#abil.com"];
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[xmlParser setDelegate:self];
[xmlParser parse];
NSLog(#"name=%#",currentUser);
statuslabel.text= currentUser;
}
Here is a tutorial on xml parsing in ios that shows how it is done. http://theappcodeblog.com/2011/05/09/parsing-xml-in-an-iphone-app-tutorial
Here is another tutorial on accessing multi level XML documents
But as far as I can see you should just replace "Result" with "URL" if this is the only URL tag in your XML, as fa as I understand NSXMLParser will handle the levels for you in this case. Of course if there is more data in this XML that you need to access you should build it like the example in the second link.

How to parse data from a website using NSXMLParser

I want to get the updates from a website based on the titles and links which is in xml format.
I have tried with the code below but it's not working. In console it is showing the message:
2011-11-03 14:45:05.987 tabbar[673:e903] * Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString
isEqualtostring:]: unrecognized selector sent to instance 0x5746830'
If I run again, the table view is loading but there is no data in the table cells.
It is showing this message at the line if ([elementName isEqualtostring:#"item"]):
program received signal SIGABRT
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
classelement = elementName;
if ([elementName isEqualtostring:#"item"])
{
itemselected = YES;
multitle = [[NSMutableString alloc]init];
mullink = [[NSMutableString alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedname:(NSString *)qName
{
if ([elementName isEqualToString:#"item"])
{
itemselected = NO;
[titlearray addObject:multitle];
[linkarray addObject:mullink];
[multitle release];
[mullink release];
[self.tbl reloadData];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (itemselected)
{
if ([classelement isEqualToString:#"title"])
{
NSLog(#"%#",string);
[multitle appendString:multitle];
}
else if([classelement isEqualToString:#"link"])
{
[multitle appendString:string];
}
}
}
If you are reading directly from a website more than likely you are getting "invalid" characters. As soon as the parser see's these invalid characters it will crash. I would suggest looking at using "HPPLE Parser". It works much better and wont crash if invalid characters come in.
Hpple information here: http://blog.objectgraph.com/index.php/2010/02/24/parsing-html-iphone-development/
Finally I got it. What I did is I have taken two NSMutableArrays and two NSMutableStrings and I appended the items to the strings, and later those strings I appended to the two arrays.
(void)viewDidLoad
{
titlearray = [[NSMutableArray alloc]init];
linkarray = [[NSMutableArray alloc]init];
NSString *rssaddress =#"http://www.greenday.com/rss";
NSURL *url = [NSURL URLWithString:rssaddress];
xmlparser = [[NSXMLParser alloc]initWithContentsOfURL:url];
[xmlparser setDelegate:self];
[xmlparser parse];
[super viewDidLoad];
}
(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
classelement = elementName;
if([elementName isEqualToString:#"item" ])
{
itemselected = YES;
titlestrng = [[NSMutableString alloc]init];
linkstrng = [[NSMutableString alloc]init];
}
}
(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"item" ])
{
itemselected = NO;
[titlearray addObject:titlestrng];
[linkarray addObject:linkstrng];
[titlestrng release];
[linkstrng release];
[self.tb reloadData];
}
}
(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(itemselected)
{
if([classelement isEqualToString:#"title"])
{
[titlestrng appendString: string];
NSLog(#"%#",titlestrng);
}
else if ([classelement isEqualToString:#"link"])
{
[linkstrng appendString:string];
NSLog(#"%#",linkstrng);
}
}
}

Resources