我无法从目标c上的URL解析xml

时间:2012-04-06 16:50:33

标签: objective-c nsxmlparser

我是目标C的初学者,我想从URL解析XML文件,我找到了一些关于NSXMLPARSER的示例代码,我编写了这段代码,但它不起作用。

请帮帮我。

我的xml文件是:

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

...我的ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <NSXMLParserDelegate>  {

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

@end

...我的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

2 个答案:

答案 0 :(得分:0)

你不应该声明这是ViewController - 这是一个非常糟糕的设计。创建一个新类(ex XMLParser:@interface XMLParser : NSObject <NSXMLParserDelegate>) 现在调用初始化方法解析。下面的示例代码:

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

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

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

    return self;
}

现在您可以声明您的方法。

答案 1 :(得分:0)

attributeDict仅包含属性值...

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

所以当你将elementName作为第一个时,attributeDict会有'name''last'和其他属性 不是子元素 sec