0

I am a beginner in objective C , I want to parse a XML file from URL , I found some sample code about NSXMLPARSER and I write this code but it do not work.

please help me.

my xml file is :

<list>
<first>apple</first>
</list>

... My ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <NSXMLParserDelegate>  {

}
@property (weak, nonatomic) IBOutlet UITextView *myTextField;

@end

...My ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController @synthesize myTextField;
- (void)parseXMLFileAtURL:(NSString *)URL { 
    NSURL * xmlURL = [NSURL URLWithString:URL];
    NSXMLParser * rssparser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [rssparser setDelegate:self];
    [rssparser parse];
}

- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName 
    attributes:(NSDictionary*)attributeDict {           

    if ([elementName isEqualToString:@"list"]) {
        // clear out our story item caches...
        myTextField.text = [attributeDict objectForKey:@"first"];
    }
}

- (void)viewDidLoad {
    NSString * path = @"http://example.com";
    [self parseXMLFileAtURL:path];
    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib. 
}

- (void)viewDidUnload {
    [self setMyTextField:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view. 
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
}

@end
C4 - Travis
  • 4,502
  • 4
  • 31
  • 56

2 Answers2

0

You shouldn't declare this is ViewController - is a very bad design. Create a new class (ex XMLParser: @interface XMLParser : NSObject <NSXMLParserDelegate>) Now call in the initializer method parse. Below sample code:

-(id)init
{
    self = [super init];

    parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"guidef" ofType:@"xml"]]];

    [parser setDelegate:self];
    [parser parse];

    return self;
}

Now you can declare your methods.

Jakub
  • 13,712
  • 17
  • 82
  • 139
  • I didn't understand - how do I call it from my UiViewController if I need to parse and return a new string? – Dejell Dec 29 '12 at 20:35
0

attributeDict holds only attribute values ...

<first name="something" last="something" > <sec>some</sec></first>

so when you get elementName as first attributeDict will have 'name' and 'last' and other attributes not the child element sec

Kamal
  • 1,122
  • 11
  • 18