绝望的NSXMLParser指导

时间:2011-12-27 19:54:40

标签: iphone objective-c xml nsxmlparser

我之前曾问过这个问题XMLParser Advice

但是我仍然无法让它正常运作....

所以我想我会从头开始:

位于某个URL的XML树看起来像这样

<result>

   //stuff that I dont need

   <title>
      //thing that I do need
   </title>

  //stuff that I dont need

   <body>
      //thing that I do need
   </body>

<result>

我怎么去解析那个? 我到目前为止的(无用的)代码可以在这个问题顶部的链接中找到。

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

编写一个简单的类,它将是解析器的委托。

@interface YourObject : NSObject <NSXMLParserDelegate> {
    NSString *title, *body;    // object attributes
    NSXMLParser *parser;       // will parse XML
    NSMutableString *strData;  // will contains string data being parsed
}

@property(readwrite, copy) NSString *title, body;

// will be used to set your object attributes
-(void)fetchValuesAtURL:(NSString *)url;

@end

fetchValuesAtURL:方法将启动解析操作。

@implementation YourObject

@synthesize title, body;

-(id)init {
    self = [super init];
    if(self) {
        title = @"";
        body = @"";
        parser = nil;
        strData = [[NSMutableString alloc] initWithCapacity:10];
    }
    return self;
}

-(void)fetchValuesAtURL:(NSString *)url {
    if(parser) {
        [parser release];
    }
    NSURL *xmlURL = [NSURL URLWithString:url];
    parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [parser setDelegate:self];
    [parser parse];
}

-(void)parser:(NSXMLParser *)parser
 didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
   qualifiedName:(NSString *)qName
      attributes:(NSDictionary *)attributeDict {
    // element is about to be parsed, clean the mutable string
    [strData setString:@""];
}

// the probably missing method
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    // content (or part of) has been found, append that to the current string
    [strData appendString:string];
}

-(void)parser:(NSXMLParser *)parser
   didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
   qualifiedName:(NSString *)qName {
    // element has been parsed, test the element name
    // and store strData accordingly
    if([elementName isEqualToString:@"title"]) {
        self.title = strData;
    }
    else {    // or else if, here you got two elements to parse
        self.body = strData;
    }
}

-(void)dealloc {
    [title release];
    [body release];
    [strData release];
    if(parser) {
        [parser release];
    }
    [super dealloc];
}

@end

然后:

YourObject *obj = [[YourObject alloc] init];
[obj fetchValuesAtURL:@"http://www.site.com/xml/url"];

NSXMLParser的代表可以做更多的事情,如Apple的Event-Driven XML Programming Guide所述。
有关委托方法的完整参考,请参阅NSXMLParserDelegate Protocol Reference