i'm trying to parse one simple XML file with NSXMLParser...here is my code..
-(void) parseXml{
NSString *XmlPath=[[NSBundle mainBundle] pathForResource:#"myXML" ofType:#"xml"];
//NSLog(#"%#",XmlPath); path found!
NSData *xml=[[NSData alloc] initWithContentsOfFile:XmlPath];
//NSLog(#"%#",Xml); outputs : xml in hexadecimal coded form
self.Xmlparser=[[NSXMLParser alloc]initWithData:xml];
//NSLog(#"%#",self.Xmlparser); outputs : some hexadecimal code
self.Xmlparser.delegate=self;
NSLog(#"%#",self.Xmlparser);
if([self.Xmlparser parse])
NSLog(#"PARSED");
else
NSLog(#"NotPARSED");
}
OUTput is "NotPARSED" ... what is going wrong?
hey you can check that its parse or not in its delegate method are bellow..
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
NSLog(#"NotPARSED");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"PARSED");
if([elementName isEqualToString:#"item"]){
currentFilm = [Film alloc];
currentNodeContent =[[NSMutableString alloc] init];
}
}
i hope this help you...
Related
I want to make a label which indicates if a band is on tour (System of a down fyi)
So I want a label in the interface to adjust to a value given on my server.
( So it needs to extract data from a (.html) file and display it as a label. )
WebViews are messy in my opinion and a label looks better.
I'd recommend using AFNetworking - http://afnetworking.com/. It will allow you to pull data from your server.
For example, you could create an XML file containing the data that you need. Then you can parse it using NSXMLParser and do whatever you need with the data.
Example:
NSURL *feedURL = [[NSURL alloc] initWithString:#"http://yourserver.com/yourxmlfile.xml"];
NSURLRequest *feedRequest = [[NSURLRequest alloc] initWithURL:feedURL];
AFXMLRequestOperation *feedOperation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:feedRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
NSLog(#"XMLRequest successful - starting parser..");
[XMLParser setDelegate:self];
[XMLParser parse];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:#"Connection Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[connectionError show];
}];
XML Example:
This is the file you will upload to your server. I use the title yourxmlfile.xml in the AFXMLRequestOperation, but call it whatever you want.
<?xml version="1.0"?>
<band>
<bandname>The Band</bandname>
<bandontour>1</bandontour>
</band>
Using NSXMLParser (delegation)
Create an ivar (in your .h) to hold the data as it is parsed.
#property (nonatomic, retain) NSString *currentProperty;
This will temporarily hold elements data, then you need to do something with it when the parser reaches didEndElement.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"bandontour"]) {
// found the <bandontour> tag
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
self.currentProperty = string;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"bandontour"]) {
// finished getting the data in <bandontour>
// do something now that you've got your data retrieved
if (self.currentProperty) int bandOnTour = self.currentProperty.intValue;
if (bandOnTour == 1) self.yourLabel.text = #"Band is on tour!";
else self.yourLabel.text = #"Not on tour.";
}
}
See NSXMLParser class reference for more information.
I am following the below link to parse the xml for login page, http://yksoftware.blogspot.in/2010/04/iphone-programming-tutorial-xml-login.html
whenever i enter the fields of username and password, it displays login failed only even when i provide the correct username and password in the textfields.
In the following code when i keep the breakpoint in loginPressed method and check, it is not entering the for loop,
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
users = [[NSMutableArray alloc]init];
NSURL *xmlURL = [NSURL URLWithString:#"http://www.mailrail.net/sample.aspx?username=naresh&password=reddy"];
xmlParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
[xmlParser setDelegate:self];
[xmlParser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"User"]) {
item = [[NSMutableDictionary alloc] init];
currentUser =[[NSMutableString alloc] init];
currentPassword =[[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"User"]) {
[item setObject:currentUser forKey:#"username"];
[item setObject:currentPassword forKey:#"password"];
[users addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"username"]) {
[currentUser appendString:string];
}
if ([currentElement isEqualToString:#"password"]) {
[currentPassword appendString:string];
}
}
-(IBAction)loginPressed:(id)sender{
for (NSMutableDictionary *val in users) {
NSMutableString *usrname = [val objectForKey:#"username"];
NSLog(#"%#",usrname);
NSMutableString *psswrd = [val objectForKey:#"password"];
usrname=[usrname stringByReplacingOccurrencesOfString:#"\n" withString:#""];
usrname=[usrname stringByReplacingOccurrencesOfString:#"\t" withString:#""];
psswrd=[psswrd stringByReplacingOccurrencesOfString:#"\n" withString:#""];
psswrd=[psswrd stringByReplacingOccurrencesOfString:#"\t" withString:#""];
if([usrname isEqualToString:[txtUsername text]]&&[psswrd isEqualToString:[txtPassword text]]){
[lblLoginStatus setText:#"Login Successful!!"];
return;
}
}
[lblLoginStatus setText:#"login failed"];
return;
}
-(IBAction)returnClicked:(UITextField *)sender{
[sender resignFirstResponder];
}
-(IBAction)clickBackground:(id)sender{
[txtPassword resignFirstResponder];
[txtUsername resignFirstResponder];
}
and returns with login failed.
Thanks in advance.
You first need to solve the parsing how to parse some thing from xml using parser and then think for loging beacuse if you have made parser then it is easy to use login form. Below is the following tutorial for XML parsing it is detailed and help you can get help.
http://www.edumobile.org/iphone/iphone-programming-tutorials/parsing-an-xml-file/
hope this helps
Just check this
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"User"]) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue:[attributeDict valueForKey:#"username"] forKey:#"username"];
[item setValue:[attributeDict valueForKey:#"password"] forKey:#"password"];
[users addObject:item];
}
}
please del other two delegates and check this
I have developed one application to fetch RSS feed. I am getting this error code 5 for some URLs where as som others are working fine.
I know this error means the xml is invalid. But for my app, I have not written any xml files by my own.
Please tell me the probable reasons for this and let me know the solution
import "RootViewController.h"
#implementation RootViewController
(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if ([stories count] == 0) {
path = #"http://172.19.58.108:8080/jwplayer/JSP/Videolist.jsp";
[self parseXMLFileAtURL:path];
}
}
-(void)parseXMLFileAtURL:(NSString *)URL{
stories = [[NSMutableArray alloc]init];
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Found file and started parsing");
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSString *errorString = [NSString stringWithFormat:#"Unable to download story feed from website (Error Code %i)", [parseError code]];
NSLog(#"Error parsing xml: %#", errorString);
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc]init];
currentTitle = [[NSMutableString alloc]init];
currentDate = [[NSMutableString alloc]init];
currentSummary = [[NSMutableString alloc]init];
currentLink = [[NSMutableString alloc]init];
}
}
-(void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"item"]) {
[item setObject:currentTitle forKey:#"title"];
[item setObject:currentDate forKey:#"date"];
[item setObject:currentSummary forKey:#"summary"];
[item setObject:currentLink forKey:#"link"];
[stories addObject:[item copy]];
NSLog(#"adding story: %#", currentTitle);
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]) {
[currentTitle appendString:string];
}
else if ([currentElement isEqualToString:#"link"]) {
[currentLink appendString:string];
}
else if ([currentElement isEqualToString:#"description"]) {
[currentSummary appendString:string];
}
else if ([currentElement isEqualToString:#"pubDate"]) {
[currentDate appendString:string];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(#"all done");
NSLog(#"stories array has %d items", [stories count]);
[newsTable reloadData];
}
Please check your library class for Rss feed parsing. Use standard library class, change the the code accordingly.
how to parse if xml attributes changes...'
for example
<Root>
<child name="", age="",phone="",address=""/>
</Root>
this is my first request from iphone through webserver.... i parsed above xml...
after that when i request the same url .. which is updated now it my xml child tag changes.
<Root>
<child name="",age="",phone="",address="",office="",mobile="",location=""/>
</Root>
extra three attributes added..
what to do with this approach .. any example please send... thanks in advance
-(void)startParsingForSendFriendRequest:(NSString *)userID Friend:(NSString*)friendID
{
NSString *urlString =[NSStringstringWithFormat:#"http:///user_id=%#&friend_id=%#",userID,friendID];
////NSLog(#"urlString : %#",urlString);
NSURL *xmlURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *itemData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
//NSString *itemString = [[[NSString alloc] initWithBytes:[itemData bytes] length:[itemData length] encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"itemString : %#",itemString);
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:itemData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
////NSLog(#"parserDidStartDocument");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
////NSLog(#"parseErrorOccurred");
NSString * errorString = [NSString stringWithFormat:#"Error (Error code %i )", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading data" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
//NSLog(#"didStartElement");
// NSLog(#"elementName : %#",elementName);
// NSLog(#"namespaceURI : %#",namespaceURI);
// NSLog(#"qualifiedName : %#",qualifiedName);
NSLog(#"attributeDict : %#",attributeDict);
[registerNewArr addObject:attributeDict];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
////NSLog(#"foundCharacters");
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
////NSLog(#"didEndElement");
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
if ([[[registerNewArr objectAtIndex:1]objectForKey:#"Transaction"]isEqualToString:#"loginxml"])
{
[(WakeuuupLoginScreenVC *)obj getRegisterResult:registerNewArr];
}
}
- (void)dealloc
{
[registerNewArr release];
[super dealloc];
}
I have made a simple rss reader. The app loads an xml atom file in an array.
Now I have added categories to my atom feed, which are first loaded in the array
What is the best way to add drill down functionality programmatically.
Now only the categories are loaded into the array and displayed.
This is the implementation code
.....
loading xml file <snip>
.....
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(#"found file and started parsing");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(#"found this element: %#", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:#"entry"]) {
// clear out our story item caches...
Categoryentry = [[NSMutableDictionary alloc] init];
currentID = [[NSMutableString alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentContent = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(#"ended element: %#", elementName);
if ([elementName isEqualToString:#"entry"]) {
// save values to an entry, then store that item into the array...
[Categoryentry setObject:currentTitle forKey:#"title"];
[Categoryentry setObject:currentID forKey:#"id"];
[Categoryentry setObject:currentSummary forKey:#"summary"];
[Categoryentry setObject:currentContent forKey:#"content"];
[categories addObject:[Categoryentry copy]];
NSLog(#"adding category: %#", currentTitle);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(#"found characters: %#", string);
// save the characters for the current item...
if ([currentElement isEqualToString:#"title"]) {
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:#"id"]) {
[currentID appendString:string];
} else if ([currentElement isEqualToString:#"summary"]) {
[currentSummary appendString:string];
} else if ([currentElement isEqualToString:#"content"]) {
[currentContent appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(#"all done!");
NSLog(#"categories array has %d entries", [categories count]);
[newsTable reloadData];
}
Apple provides a good sample app for demonstrating a drill-down tableview:
SimpleDrillDown
Write a generic UITableViewController subclass that takes an array of values. Then, when the user taps on a row, get the array of posts associated with the selected category and pass that to a new view controller. Then, push the view controller onto the stack, using [[self navigationController] pushViewController:nextViewController animated:YES];.
I've just released an open source RSS/Atom Parser for iPhone and hopefully it might be of some use.
I'd love to hear your thoughts on it too!