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];
Related
I am trying NSXMLParser for getting values from an XML for first time. But I have a problem.
Below my XML:
<Library>
<Book>
<ID>1</ID>
<TITLE>Test</TITLE>
</Book>
</Library>
and parser code:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedNam(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Book"])
{
NSLog(#"%#", [attributeDict valueForKey:#"ID"]);
}
}
The result ID is null. Can you help me please?
Unfortunately, NSXMLParser doesn't work this way. It traverses over the elements in XML in document order, so by the time the "Book" element starts, it hasn't reached the "ID" element yet. Your code would work if the XML looked like
<Book Id="1">
...
</Book>
but I suppose you have no control over the XML. Then you need a more sophisticated solution. I believe the following would work:
Add these instance variables
NSString *currentElement, *bookID, *bookTitle;
NSMutableString *elementValue;
Implement the following methods:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedNam(NSString *)qName attributes:(NSDictionary *)attributeDict {
currentElement = elementName;
elementValue = nil;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
// Append characters to element value
if (!elementValue) elementValue = [NSMutableString stringWithCapacity:100];
[elementValue appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName {
if ([#"Id" isEqualToString:elementName]) {
bookID = [elementValue copy];
} else if ([#"Title" isEqualToString:elementName]) {
bookTitle = [elementValue copy];
} else if ([#"Book" isEqualToString:elementName]) {
// end of Book element, do something with bookID and bookTitle
}
}
Follow the below code.You will understand.
In your .h part
//Step 1 : Add the Delegate classes
First of all you should add <NSXMLParserDelegate>
//Step 2 : Create necessary objects
NSXMLParser *parser;
NSMutableData *ReceviedData;
NSMutableString *currentStringValue;
NSMutableArray *arrayID;
In your .m part
//Step 3 - Allocate your all Arrays in your viewDidLoad method
arrayId = [NSMutableArray alloc]init];
//Step 4 - Create Connection in your viewDidLoad Like
[self createConnection:#"http://www.google.com"];//give your valid url.
-(void)createConnection:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
//Step 5 - parser delegate methods are using NSURLConnectionDelegate class or not.
BOOL success;
if (!parser)
{
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
parser.delegate = self;
parser.shouldResolveExternalEntities = YES;
success = [parser parse];
NSLog(#"Success : %c",success);
}
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"Current Element Name : %#",elementName);
if ([elementName isEqualToString:#"ID"])
{
NSLog(#"The Result is==%#",elementName);
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentStringValue = [[NSMutableString alloc] initWithString:string];
NSLog(#"Current String Value : %#",currentStringValue);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"ID"])
{
[arrayResult addObject:currentStringValue];
}
currentStringValue = nil;
}
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];
}
I have a xml to parse:
<media:content url='http://www.youtube.com/v/x5cBBXXFAPQ?version=3&f=playlists&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='391' yt:format='5'/><media:content url='rtsp://r5---sn-4g57kuee.c.youtube.com/CiULENy73wIaHAn0AMV1BQGXxxMYDSANFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='391' yt:format='1'/><media:content url='rtsp://r5---sn-4g57kuee.c.youtube.com/CiULENy73wIaHAn0AMV1BQGXxxMYESARFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='391' yt:format='6'/><media:description type='plain'>Bohemian Rhapsody
how can i get the first url from content ?
First you need to refer the Apple Documention
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/index.html
- (void)viewDidLoad
{
NSURL *url = [[NSURL alloc]initWithString:#"yourURL"];
NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
[parser setDelegate:self];
BOOL result = [parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(#\"Did start element\");
if ( [elementName isEqualToString:#"media:content"])
{
NSLog(#"found URL",[attributeDict objectForKey:#"url"]);//here u will get the url u want
return;
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(#"Did end element");
if ([elementName isEqualToString:#"media"])
{
NSLog(#"rootelement end");
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"Value %#",string);
}
It just overview about the delegate methods of XML not the solution..Refer the Document..
runnable sample:
edited based on comment...
#import <Foundation/Foundation.h>
#interface MyClass : NSObject<NSXMLParserDelegate>
#end
#implementation MyClass
- (instancetype)init {
self = [super init];
id xml = #"<media:content url='http://www.youtube.com/v/x5cBBXXFAPQ?version=3&f=playlists&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='391' yt:format='5'/><media:content url='rtsp://r5---sn-4g57kuee.c.youtube.com/CiULENy73wIaHAn0AMV1BQGXxxMYDSANFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='391' yt:format='1'/><media:content url='rtsp://r5---sn-4g57kuee.c.youtube.com/CiULENy73wIaHAn0AMV1BQGXxxMYESARFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='391' yt:format='6'/><media:description type='plain'>Bohemian Rhapsody";
id d = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *p = [[NSXMLParser alloc] initWithData:d];
p.delegate = self;
[p parse];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"media:content"]) {
static BOOL first = YES;
if(first) {
NSLog(#"%#", attributeDict[#"url"]);
first = NO;
}
}
}
#end
int main(int argc, const char * argv[]) {
#autoreleasepool {
id c = [[MyClass alloc] init];
}
return 0;
}
I'm trying to parse this xml file. The problem I'm having is that I'd like to use the
-(void)parser:(NSXMLParser*)parser didStartElement ...
to drill down into several levels of this xml file.
This is what I have so far:
#pragma didStartElement (from the parser protocol)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// Choose the tag
if ([elementName isEqualToString:#"item"]) {
NSString *firstName = [attributeDict valueForKey:#"firstname"];
NSString *lastName = [attributeDict valueForKey:#"lastname"];
NSString *birthDay = [attributeDict valueForKey:#"birthday"];
Politician *politician = [[Politician alloc] initWithName:firstName lName:lastName bDay:birthDay];
if (politician != nil) {
[people addObject:politician];
}
}
}
The problem is that this code does not drill down. Is there a way to selectively start the parsing from a specific tag (say: person) and check for the keys of that tag or to rewrite the "elementName's" value so I can use multipe if statements? What's the right way of doing this? Thanks much.
You couldnt get the firstname,lastname,etc in your attributeDict. Attribute dictionary holds values like in the below format
<count n="1">
In the above example attributeDict holds the value for n
In order to parse the given xml, you can use the below code.
Declare the objects
Politician *politician;
NSString *curElement;
NSMutableArray *politicians;
BOOL isCongressNumbers;
Initialize the politicians in viewDidLoad
politicians = [[NSMutableArray alloc]init];
Add the delegate methods
#pragma mark - NSXMLParser Delegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"item"]) {
politician = [[Politician alloc]init];
} else if ([elementName isEqualToString:#"congress_numbers"]) {
isCongressNumbers = YES;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
curElement = string;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"item"] && !isCongressNumbers) {
[politicians addObject:politician];
} else if ([elementName isEqualToString:#"firstname"]) {
politician.name = curElement;
} else if ([elementName isEqualToString:#"lastname"]) {
politician.lName = curElement;
} else if ([elementName isEqualToString:#"birthday"]) {
politician.bDay = curElement;
} else if ([elementName isEqualToString:#"congress_numbers"]) {
isCongressNumbers = NO;
}
}
You can
1) new a Politician in the didStartElement method and assign the element name in one instance variable.
2) assign the properties of Politician in the foundCharacters according to the instance variable you assigned in 1).
3) add the Politician to the people in the didEndElement.
Hope this is helpful.
The sample code is as follows:
declare some instance variables:
Politican *politican;
NSString *currentElement;
NSMutableArray *politicians;
init the arrays:
politicians = [[NSMutableArray alloc] init];
implement the delegate methods.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
currentElement = elementName;
if ([elementName isEqualToString:#"item"]) {
politician = [[Politician alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if([string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length<1)
return; // avoid some white space
if ([currentElement isEqualToString:#"firstname"]) {
politician.firstname = string;
} else if ([currentElement isEqualToString:#"lastname"]) {
politician.lastname = string;
} else if ([currentElement isEqualToString:#"birthday"]) {
politician.birthday = string;
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"item"]) {
[politicians addObject:politician];
}
}
Anyway this is just a sample, you'd better write all the if else statements according to your xml.
In your xml file, there are several tags named the same item. you can try to make one more instance variable to store the previous tag to make the difference and do the assignments.
In.h file
#property (strong, nonatomic) NSXMLParser *xmlParser;
#property (nonatomic, retain) NSMutableDictionary *lResponseDict;
#property (nonatomic, weak) NSString *currentElement;
NSString* UDID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSLog(#"UDID:: %#", UDID);
NSString *urlString = [NSString stringWithFormat:#"urlHere"];
NSString *jsonString = [NSString stringWithFormat:LOGIN,self.cUsernameTxtFld.text,self.cPasswordTxtFld.text,UDID];
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html" forHTTPHeaderField:#"Accept"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
self.xmlParser = [[NSXMLParser alloc] initWithData:urlData];
self.xmlParser.delegate = self;
// Start parsing.
[self.xmlParser parse];
}
#pragma mark - NSXML Parsar Delegate Methods.
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
// NSLog(#"Parsing Initiated.");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
self.currentElement = elementName;
if([elementName isEqualToString:#"data"])
{
// NSLog(#"%#",elementName);
self.lResponseDict = [[NSMutableDictionary alloc]init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"data"])
{
// NSLog(#"%#",elementName);
NSLog(#"Final Dict: %#", _lResponseDict);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//NSLog(#"%#", string);
[_lResponseDict setObject:string forKey:_currentElement];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
}
Hope you are getting the URL data ... so with SMXMLParser, it is easier to parse using one by one node ...
In the below mentioned example, I am using AFNetworking with SMXMLParser . Hope you get the idea ....
NSString *soapRequest=[NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
// Your parameters here …. //
"</soap:Body>\n"
"</soap:Envelope>\n"];
NSString *urlStr = #"Your URL";
NSURL *urlNew = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request=[appDel generateRequestWithUrl:urlNew request:soapRequest];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error=nil;
dictCarList = [[NSMutableDictionary alloc]init];
SMXMLDocument *document=[[SMXMLDocument alloc]initWithData:operation.responseData error:&error];
if (error) {
NSLog(#"Error while parsing the document: %#", error);
[indicatorView removeFromSuperview];
return;
}
count++;
SMXMLElement *element1 = [document.root childNamed:#"objects"];
SMXMLElement *element2 = [element1 childNamed:#"The Tag you want to get"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error:%#",error);
}];
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.