且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 NSXMLParser 中解析 xml

更新时间:2022-02-03 22:19:18

实现NSXMLParser需要实现它的delegate方法.

For implementing NSXMLParser you need to implement delegate method of it.

首先以这种方式启动 NSXMLParser.

First of all initiate NSXMLParser in this manner.

- (void)viewDidLoad {

    [super viewDidLoad];

    rssOutputData = [[NSMutableArray alloc]init];

    //declare the object of allocated variable
    NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@""]];// URL that given to parse.

    //allocate memory for parser as well as 
    xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
    [xmlParserObject setDelegate:self];

    //asking the xmlparser object to beggin with its parsing
    [xmlParserObject parse];

    //releasing the object of NSData as a part of memory management
    [xmlData release];

}
//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
    if( [elementName isEqualToString:@"question"])
    {

         strquestion = [[NSMutableString alloc] init];

    }
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
       // init the ad hoc string with the value     
     currentElementValue = [[NSMutableString alloc] initWithString:string];
  } else {
     // append value to the ad hoc string    
    [currentElementValue appendString:string];
  }
  NSLog(@"Processing value for : %@", string);
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if( [elementName isEqualToString:@"question"])
    {
        [strquestion setString:elementName];
    }

 [currentElementValue release];
  currentElementValue = nil;
}

当解析器对象遇到特定元素的结尾时,将上述委托方法发送给其委托.在此方法 didEndElement 中,您将获得 question 的值.

The above delegate method is sent by a parser object to its delegate when it encounters an end of specific element. In this method didEndElement you will get value of question.