I am trying to parse data from xml parsing but it could not show anything ..
-(void)viewDidLoad {
[super viewDidLoad];
self.mdata=[[NSMutableData alloc]init];
marr=[[NSMutableArray alloc]init];
mwebcall =[[NSMutableArray alloc]init];
NSString *urlstr=#"http://www.espncricinfo.com/rss/content/story/feeds/6.xml";
NSURL *url1 = [NSURL URLWithString:urlstr];
NSURLRequest *urlrequest=[[NSURLRequest alloc]initWithURL:url1 ];
con = [[NSURLConnection alloc]initWithRequest:urlrequest delegate:self];
[con start];
}
// Do any additional setup after loading the view, typically from a nib.
//#pragma mark-xmlmethods
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.xmlparse=[[NSXMLParser alloc]initWithData:mdata];
self.xmlparse .delegate=self ;
[self.xmlparse parse];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"item"])
{
str=#"item";
}
else if ([elementName isEqualToString:#"title"])
{
str=#"title";
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([str isEqualToString:#"item"])
{
str1=#"";
str1=[str1 stringByAppendingString:string];`enter code here`
}
if ([str isEqualToString:#"title"])
{
str1=#"";
str1=[str1 stringByAppendingString:string];
NSLog(#"%#",str1);
}`enter code here`
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([str isEqualToString:#"item"])
{
[mwebcall addObject:str1];
NSLog(#"%#",str1);
}
if ([str isEqualToString:#"title"])
{
[mwebcall addObject:str1];
NSLog(#"%#",str1);
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
}
Use this GitHub library.
OR
NSString *url=#"http://www.lancers.jp/work";
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSDictionary *dict=[XMLParser dictionaryForXMLData:data error:nil];
NSLog(#"%#",[dict description]);
Use this code and create the following files
XMLParser.h
#import <Foundation/Foundation.h>
#interface XMLParser : NSObject<NSXMLParserDelegate>
{
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError **errorPointer;
}
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;
#end
XMLParser.m
#import "XMLParser.h"
NSString *const kXMLReaderTextNodeKey = #"text";
#interface XMLParser (Internal)
- (id)initWithError:(NSError **)error;
- (NSDictionary *)objectWithData:(NSData *)data;
#end
#implementation XMLParser
#pragma mark -
#pragma mark Public methods
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{
XMLParser *reader = [[XMLParser alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithData:data];
[reader release];
return rootDictionary;
}
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [XMLParser dictionaryForXMLData:data error:error];
}
#pragma mark -
#pragma mark Parsing
- (id)initWithError:(NSError **)error
{
if (self = [super init])
{
errorPointer = error;
}
return self;
}
- (void)dealloc
{
[dictionaryStack release];
[textInProgress release];
[super dealloc];
}
- (NSDictionary *)objectWithData:(NSData *)data
{
// Clear out any old data
[dictionaryStack release];
[textInProgress release];
dictionaryStack = [[NSMutableArray alloc] init];
textInProgress = [[NSMutableString alloc] init];
// Initialize the stack with a fresh dictionary
[dictionaryStack addObject:[NSMutableDictionary dictionary]];
// Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
BOOL success = [parser parse];
// Return the stack's root dictionary on success
if (success)
{
NSDictionary *resultDict = [dictionaryStack objectAtIndex:0];
return resultDict;
}
return nil;
}
#pragma mark -
#pragma mark NSXMLParserDelegate methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// Get the dictionary for the current level in the stack
NSMutableDictionary *parentDict = [dictionaryStack lastObject];
// Create the child dictionary for the new element, and initilaize it with the attributes
NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
[childDict addEntriesFromDictionary:attributeDict];
// If there's already an item for this key, it means we need to create an array
id existingValue = [parentDict objectForKey:elementName];
if (existingValue)
{
NSMutableArray *array = nil;
if ([existingValue isKindOfClass:[NSMutableArray class]])
{
// The array exists, so use it
array = (NSMutableArray *) existingValue;
}
else
{
// Create an array if it doesn't exist
array = [NSMutableArray array];
[array addObject:existingValue];
// Replace the child dictionary with an array of children dictionaries
[parentDict setObject:array forKey:elementName];
}
// Add the new child dictionary to the array
[array addObject:childDict];
}
else
{
// No existing value, so update the dictionary
[parentDict setObject:childDict forKey:elementName];
}
// Update the stack
[dictionaryStack addObject:childDict];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// Update the parent dict with text info
NSMutableDictionary *dictInProgress = [dictionaryStack lastObject];
// Set the text property
if ([textInProgress length] > 0)
{
[dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];
// Reset the text
[textInProgress release];
textInProgress = [[NSMutableString alloc] init];
}
// Pop the current dict
[dictionaryStack removeLastObject];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// Build the text value
[textInProgress appendString:string];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
// Set the error pointer to the parser's error object
*errorPointer = parseError;
}
#end
Related
Its my xml file in that I've data
<?xml version="1.0" encoding="UTF-8"?>
<locations>
<location id="1">
<title>United Arab Emirates</title>
<latitude>23.424076</latitude>
<longitude>53.847818</longitude>
</location>
<location id="2">
<title>Afghanistan</title>
<latitude>33.93911</latitude>
<longitude>67.709953</longitude>
</location>
<location id="3">
<title>Australia</title>
<latitude>-25.274398</latitude>
<longitude>133.775136</longitude>
</location>
<location id="4">
<title>Bangladesh</title>
<latitude>23.684994</latitude>
<longitude>90.356331</longitude>
</location>
</locations>
===============================
Its my .m file in that I've written the code
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self dataParsing];
NSLog(#"%#",locSMutArr);
[self setUpMapMethod];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)dataParsing{
NSString *strFile=[[NSBundle mainBundle] pathForResource:#"xmlPractise1" ofType:#"xml"];
NSData *dataObj=[NSData dataWithContentsOfFile:strFile];
NSXMLParser *parseObj=[[NSXMLParser alloc]initWithData:dataObj];
parseObj.delegate=self;
[parseObj parse];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - NSXMLParser Delegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{
if ([elementName isEqualToString:#"locations"]) {
locSMutArr=[[NSMutableArray alloc]init];
}
else if([elementName isEqualToString:#"location"]){
locMutDic=[[NSMutableDictionary alloc]init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if (refString==nil) {
refString=[[NSMutableString alloc]init];
}
else{
refString=[NSMutableString stringWithFormat:#"%#%#",refString,string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{
if ([elementName isEqualToString:#"latitude"] || [elementName isEqualToString:#"longitude"]) {
[locMutDic setValue:refString forKey:elementName];
}
else if ([elementName isEqualToString:#"location"]){
[locSMutArr addObject:locMutDic];
}
refString=nil;
}
-(void)setUpMapMethod{
for (int i=0; i<4; i++) {
CLLocationCoordinate2D CLLocObj;
CLLocObj.latitude=[locSMutArr indexOfObject:[locMutDic valueForKey:#"latitude"]];
CLLocObj.longitude=[locSMutArr indexOfObject:[locMutDic valueForKey:#"longitude"]];
MKCoordinateRegion viewRegion=MKCoordinateRegionMakeWithDistance(CLLocObj, 100, 100);
[_mapOutlet setRegion:viewRegion];
MKPointAnnotation *annotaionObj=[[MKPointAnnotation alloc]init];
[annotaionObj setCoordinate:CLLocObj];
[_mapOutlet addAnnotation:annotaionObj];
}
}
#end
I want to use for loop for creating CLLocationCoordinate2D object for all value of lat and lon that in dictionary of xml .
And also annotate there all locations .
That all
============================
It my .h file where I've declare all objs.
#interfaceViewController:UIViewController<NSXMLParserDelegate,CLLocationManagerDele gate,MKMapViewDelegate>{
NSMutableArray *locSMutArr;
NSMutableDictionary *locMutDic;
NSMutableString *refString;
NSMutableArray *mutLatArr;
}
#property (weak, nonatomic) IBOutlet MKMapView *mapOutlet;
#end
So here is the Code which works for me
import "ViewController.h"
#interface ViewController ()
#property(nonatomic,strong)NSMutableArray *locations;
#property(nonatomic,strong)NSMutableDictionary *location;
#property(nonatomic,strong)NSString *openElement;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_locations = [[NSMutableArray alloc]init];
[self parseData];
[self logData];
[self setupMap];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)logData{
NSLog(#"%#",_locations);
}
-(void)parseData{
NSString *path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"xml"];
NSData *data = [[NSData alloc]initWithContentsOfFile:path];
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
parser.delegate = self;
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{
if([elementName isEqualToString:#"location"])
_location = [[NSMutableDictionary alloc]init];
else if([elementName isEqualToString:#"locations"])
NSLog(#"Start");
else
_openElement = elementName;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(![string containsString:#"\n"])
[_location setObject:string forKey:_openElement];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{
if([elementName isEqualToString:#"location"])
[_locations addObject:_location];
}
- (void)parser:(NSXMLParser *)parser foundAttributeDeclarationWithName:(NSString *)attributeName forElement:(NSString *)elementName type:(nullable NSString *)type defaultValue:(nullable NSString *)defaultValue{
NSLog(#"%#",attributeName);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setupMap{
for(NSMutableDictionary *dict in _locations){
CLLocationCoordinate2D CLLocObj;
CLLocObj.latitude=[(NSString*)[dict valueForKey:#"latitude"] floatValue];
CLLocObj.longitude=[(NSString*)[dict valueForKey:#"longitude"] floatValue];
MKCoordinateRegion viewRegion=MKCoordinateRegionMakeWithDistance(CLLocObj, 100000, 100000);
[_mapView setRegion:viewRegion];
MKPointAnnotation *annotaionObj=[[MKPointAnnotation alloc]init];
[annotaionObj setCoordinate:CLLocObj];
[annotaionObj setTitle:[dict valueForKey:#"title"]];
[_mapView addAnnotation:annotaionObj];
}
}
This is the output of my NSMutableArray with the NSMutableDictionary
(
{
latitude = "23.424076";
longitude = "53.847818";
title = "United Arab Emirates";
},
{
latitude = "33.93911";
longitude = "67.709953";
title = Afghanistan;
},
{
latitude = "-25.274398";
longitude = "133.775136";
title = Australia;
},
{
latitude = "23.684994";
longitude = "90.356331";
title = Bangladesh;
}
)
I am trying to develop an XML parser in objective-C using the method described in http://wiki.cs.unh.edu/wiki/index.php/Parsing_XML_data_with_NSXMLParser.
I have coded up the entire flow but the delegate call back methods just won't respond!
Please take a look at the following code blocks and let me know if you could figure out any mistakes/errors...
Parser is being called from:
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"cache" ofType:#"xml"];
NSLog(#"Path location is : %#",filePath);
NSData* xmlData = [NSData dataWithContentsOfFile:[NSURL URLWithString:filePath]];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlData];
if(nsXmlParser!=NULL)
{
NSLog(#"parser is %#",nsXmlParser);
}
HDDataXML *parser = [[HDDataXML alloc] initXMLParser];
[nsXmlParser setDelegate:parser];
BOOL success = [nsXmlParser parse];
// test the result
if (success)
{
NSLog(#"No errors - effects count : i");
} else
{
NSLog(#"Error parsing document!");
}
All I see here is Error parsing document! The filePath variable is OK and the parser is not null.
Now, in the delegate's .h file:
#import <Foundation/NSObject.h>
#import "EffectsCache.h"
#class EffectsCache;
#interface HDDataXML : NSObject<NSXMLParserDelegate>
{
EffectsCache *effectsHandler;
NSMutableString *currentElementValue;
NSMutableArray *effects;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string ;
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName;
- (HDDataXML *) initXMLParser;
#property (nonatomic, retain) EffectsCache *effectsHandler;
#property (nonatomic, retain) NSMutableArray *effects;
#end
And in the implementation of the delegate in .m:
#import "HDDataXML.h"
#implementation HDDataXML
#synthesize effects, effectsHandler;
- (HDDataXML *) initXMLParser
{
[super init];
effects = [[NSMutableArray alloc] init];
return self;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
NSLog(#"started parsing");
if ([elementName isEqualToString:#"effects"]) {
NSLog(#"effects element found – create a new instance of EffectsCache class...");
effectsHandler = [[EffectsCache alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"mid parsing");
if (!currentElementValue)
{
currentElementValue = [[NSMutableString alloc] initWithString:string];
}
else
{
[currentElementValue appendString:string];
}
NSLog(#"Processing value for : %#", string);
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
NSLog(#"done parsing");
if ([elementName isEqualToString:#"effects"])
{
return;
}
if ([elementName isEqualToString:#"effect"])
{
[effectsHandler addObject:effects];
[effectsHandler release];
effectsHandler = nil;
}
else
{
NSLog(#"cuurent value - %#",currentElementValue);
[effects setValue:currentElementValue forKey:elementName];
}
[currentElementValue release];
currentElementValue = nil;
}
Point is, the call back methods are not working.
Please help me find the bug.
Thanks in advance.
nsXmlParser.delegate = self;
[nsXmlParser parse];
and dont forget in the .h file to call the delegate
<NSXMLParserDelegate>
Ok... I solved it, finally:
As suggested by Martin R, I changed the code for calling the delegate:
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"effects_cache" ofType:#"xml"];
NSLog(#"Path location is : %#",filePath);
NSData* xmlData = [NSData dataWithContentsOfFile:filePath];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:xmlData];
Before doing this modification, the xmlData was null.
One other small modification was needed:
change:
[effectsHandler addObject:effects];
TO
[effects setValue:currentElementValue forKey:elementName];
I'm parsing a very simple XML document with XCode. Sometimes it works just fine, other times it returns this:
document.cookie='lllllll=9bb65648lllllll_9bb65648; path=/';window.location.href=window.location.href;
Here is my header file:
#interface NewsViewController : UIViewController{
NSXMLParser *rssParser;
NSMutableArray *articles;
NSMutableDictionary *item;
NSString *currentElement;
NSMutableString *ElementValue;
BOOL errorParsing;
}
#property (weak, nonatomic) IBOutlet UILabel *newsText;
#property (retain) NSMutableString *theString;
- (void)parseXMLFileAtURL:(NSString *)URL;
#end
Here is my implementation code:
-(void)viewDidLoad{
[self parseXMLFileAtURL:#"http://www.domain.com/news.xml"];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"File found and parsing started");
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
NSString *agentString = #"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:URL]];
[request setValue:agentString forHTTPHeaderField:#"User-Agent"];
NSData *xmlFile = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
articles = [[NSMutableArray alloc] init];
errorParsing=NO;
rssParser = [[NSXMLParser alloc] initWithData:xmlFile];
[rssParser setDelegate:self];
// You may need to turn some of these on depending on the type of XML file you are parsing
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString *errorString = [NSString stringWithFormat:#"Error code %i", [parseError code]];
NSLog(#"Error parsing XML: %#", errorString);
errorParsing=YES;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
ElementValue = [[NSMutableString alloc] init];
if ([elementName isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[ElementValue appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]) {
[articles addObject:[item copy]];
} else {
[item setObject:ElementValue forKey:elementName];
NSLog (#"--%#",ElementValue);
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
if (errorParsing == NO)
{
NSLog(#"XML processing done!");
theString=[NSString stringWithFormat:#"%#",ElementValue];
NSLog (#"Parsed: %#",theString);
} else {
NSLog(#"Error occurred during XML processing");
}
}
I'm fairly stumped, but I'm sure it must be something simple I can't see. Any tips?
the response you are trying to parse (probably) is not in XML.
NSLog your xml responses, and see whats being returned by the server when it returns the strange code. Validate the xml before parsing it.
I have parsed the xml file.
The console is showing the parsed elements correctly but the array is showing null.
- (ParserClass *) initXMLParser
{
//[super init];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser: (NSXMLParser *)parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"note"]) {
//Initialize the array.
appDelegate.testArray = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:#"to"]) {
aTest = [[Test alloc] init];
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(#"Processing Value: %#", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"Books"])
return;
if([elementName isEqualToString:#"note"]) {
[appDelegate.testArray addObject:aTest];
//[aBook release];
aTest = nil;
}
else
[aTest setValue:currentElementValue forKey:elementName];
//[currentElementValue release];
currentElementValue = nil;
}
#end
Try to change your initialization to:
- (ParserClass *) initXMLParser {
self=[super init];
if(self !=nil){
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// init array of user objects here
appDelegate.testArray = [[NSMutableArray alloc] init];
}
return self;
}
And,if your xml is:
<books>
<note>
<something>cccc</something>
</note>
<note>
<something>cccc</something>
</note>
</books>
So you need change:
-(void)parser: (NSXMLParser *)parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"note"]) {
aTest = [[Test alloc] init];
//if you have attributes, you can extract them here:
// user.att = [[attributeDict objectForKey:#"<att name>"] ...];
}
NSLog(#"Processing Element: %#", elementName);
}
And to get your array you must do something like this:
//Data store your xml
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:Data];
ParserClass *parser = [[ParserClass alloc] initXMLParser];
//delegate your parser
[nsXmlParser setDelegate:parser];
//it's doing parsing
BOOL success = [nsXmlParser parse];
if (success)
{
NSMutableArray *someArray = [parser appDelegate.testArray ];
NSLog(#"%#",someArray );
} else
{
NSLog(#"Error parsing document!");
}
try it , it working for me...
?xml version="1.0" encoding="UTF-8" ?> <IPAD version="1.0">
<articleSnapshot>
<item>
<categoryName>Kerala</categoryName>
<oid>2915</oid>
<title>ÎÆcÈÏ¢: ÄßøáJW ÕçKAá¢</title>
<thumbImage>http://122.248.234.55/v3/repository/images/news/bar-liquor_thuthumb_2915.jpg</thumbImage>
<shortDescription>ÎÆcÈÏÕᢠ¥Äßæa dÉ~cÞÉÈÕáÎÞÏß ÌtæMGí ©ÏVK ÕßÎVÖÈBZ ÏáÁß®Ëá¢...</shortDescription>
</item>
</articleSnapshot>
</IPAD>
I want to parse this xml file and display it in viewdidload.i have completed the coding.but cant display in image view and textview seperately.Please help me.
This is how I parse an XML file very similar to yours. This basically converts the XML into a plist file.
#pragma mark - Delegate Received
-(void)parsingComplete:(XMLDataSource*)theParser {
NSArray *categoryArray = [theParser getCategories];
[categoryArray writeToFile:PLIST atomically:YES];
}
- (void)receivedItems:(NSArray *)theItems {
NSMutableArray *dataItems = [[NSMutableArray alloc] init];
[dataItems addObjectsFromArray:[NSArray arrayWithContentsOfFile:PLIST]];
NSDictionary * dataItem = [dataItems objectAtIndex:categoryIndex];
data_ = [dataItem objectForKey:#"images"];
}
#pragma mark - Parsing Delegates
- (void)parse:(NSData *)data withDelegate:(id)sender onComplete:(SEL)callback
{
parentDelegate = sender;
onCompleteCallback = callback;
loading = YES;
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
parsed = NO;
loading = NO;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSString *element = [elementName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
currentElement = element;
if ([[currentElement lowercaseString] isEqual:#"image"]) {
inImage = YES;
itemsDictionary = [[NSMutableDictionary alloc] init];
[itemsDictionary addEntriesFromDictionary:attributeDict];
}
if ([[currentElement lowercaseString] isEqual:#"category"]) {
inCategory = YES;
categoryDictionary = [[NSMutableDictionary alloc] init];
[categoryDictionary addEntriesFromDictionary:attributeDict];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
NSString *element = [elementName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([[element lowercaseString] isEqual:#"image"]) {
inImage = NO;
[items addObject:[itemsDictionary copy]];
}
if ([[element lowercaseString] isEqual:#"category"]) {
inCategory = NO;
[categoryDictionary setObject:[items copy] forKey:#"images"];
[items removeAllObjects];
[categories addObject:[categoryDictionary copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSString *stringValue = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *element = [currentElement stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
/* skip over blank elements. */
if (stringValue == nil || [stringValue isEqual:#""]) {
return;
}
if (element != nil && [element length] > 0) {
if (inImage) {
if ([itemsDictionary objectForKey:element] != nil) {
[itemsDictionary setObject:[NSString stringWithFormat:#"%#%#", [itemsDictionary objectForKey:element], stringValue]
forKey:element];
} else {
[itemsDictionary setObject:stringValue forKey:element];
}
} else if ((!inImage) && (inCategory)) {
if ([categoryDictionary objectForKey:element] != nil) {
[categoryDictionary setObject:[NSString stringWithFormat:#"%#%#", [categoryDictionary objectForKey:element], stringValue]
forKey:element];
} else {
[categoryDictionary setObject:stringValue forKey:element];
}
} else {
if ([root objectForKey:element] != nil) {
[root setObject:stringValue forKey:element];
}
}
}
}
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSError * err;
if(![[NSFileManager defaultManager] fileExistsAtPath:PLIST]) {
[[NSFileManager defaultManager] removeItemAtPath:PLIST error:&err];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
parsed = YES;
loading = NO;
if ([parentDelegate respondsToSelector:onCompleteCallback]) {
[parentDelegate performSelector:onCompleteCallback withObject:self];
}
if ([self respondsToSelector:#selector(receivedItems:)])
[self receivedItems:items];
else
SHOW_ALERT(#"parserDidEndDocument:", #"receivedItems: not responding!", nil, #"Okay", nil)
}
#pragma mark -
#pragma mark Setters / Getters
- (id)delegate {
return self;
}
- (void)setDelegate:(id)new_delegate {
_delegate = self;
}
- (BOOL)isSuccessful {
return success;
}
- (BOOL)isLoading {
return loading;
}
- (BOOL)isParsed {
return parsed;
}
- (NSArray *)getCategories {
return categories;
}
- (NSDictionary *)getRoot {
return root;
}
- (void)dealloc {
[super dealloc];
}