Question

In my app i'm using TBXML parser where i need to get a value from xml file and print it on the label...This is my xml file in server

 <gold>
 <price>
 <title>22 K Gold</title>
 </price>
 <price>
 <title>24 K Gold</title>
 </price>
 </gold>

any my Viewcontroller.h looks like

#import <UIKit/UIKit.h>
#import "TBXML.h"

 @interface ViewController : UIViewController{

IBOutlet UILabel *lab;
TBXML *tbxml;
}



@end

and my Viewcontrooler.m looks like

 - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://www.abcde.com/sample.xml"]];
 tbxml = [[TBXML alloc]initWithXMLData:xmlData];


TBXMLElement * root = tbxml.rootXMLElement;

if (root)
{
    TBXMLElement * elem_PLANT = [TBXML childElementNamed:@"price" parentElement:root];
    while (elem_PLANT !=nil)
    {
        TBXMLElement * elem_BOTANICAL = [TBXML childElementNamed:@"title" parentElement:elem_PLANT];
        NSString *botanicalName = [TBXML textForElement:elem_BOTANICAL];
        lab.text=[NSString stringWithFormat:@"re %@", botanicalName];

        elem_PLANT = [TBXML nextSiblingNamed:@"price" searchFromElement:elem_PLANT]; 

        elem_BOTANICAL = [TBXML childElementNamed:@"title" parentElement:elem_PLANT]; 

        botanicalName = [TBXML textForElement:elem_BOTANICAL];
        lab1.text=[NSString stringWithFormat:@"re %@", botanicalName];
    }
}

}

i'm getting BAD_ACCESS thread.Am i missing anything...Help pls...

Was it helpful?

Solution

lab.text=[NSString stringWithFormat:@"re %@",elem_BOTANICAL];

Edit 1.0:

lab.text=[NSString stringWithFormat:@"re %@", botanicalName];

Edit 2.0:

lab.text=[NSString stringWithFormat:@"re %@", botanicalName];

NSString *plantName = [TBXML textForElement: elem_PLANT];

lab1.text=[NSString stringWithFormat:@"re %@", plantName];

OTHER TIPS

First of all I recommend you to parse your XML file in a separate method, so that your View will not mess with your Model. Create an object model for your XML item. Then, for instance, in one method you fill an array with objects that represent your items in XML file. And only then, when you retrieve those objects by parsing XML, you should bind this array with your view.

The second thing is you should put this line

elem_PLANT = [TBXML nextSiblingNamed:@"price" searchFromElement:elem_PLANT];

at the end of while cycle, because in the first iteration you work with the first item only, that was retrieved before while cycle began. So, if you put it in the middle, as you did, at some moment, at the end of parsing XML, the next lines after this line will work with a nil object.

The third thing is that before taking text from TBXMLElement, you should check if it is not nil:

NSString *plantName;
if (elem_PLANT) {
 plantName = [TBXML textForElement: elem_PLANT]; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top