在NSXMLParser中解析xml

5

我读了很多如何从xml文件中获取文本的例子,但是并不知道如何做。这是一个示例xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<questions>
    <set>
        <question>Question</question>
        <answer>Answer</answer>
    </set>
</questions>

使用-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI,最简单的方法是如何获取QuestionAnswer的值? 我已经连接了解析器委托并完成了所有相关工作。

4个回答

13
实现NSXMLParser需要实现其委托方法。首先,以这种方式启动NSXMLParser。
- (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的值。


1
foundCharacters 中漏掉了一个 if 条件 :) if (currentElementValue == nil) - GoodSp33d
有人最近使用过这段代码吗?我一直收到“使用了未声明的标识符xmlParserObject”的错误。是否缺少IMPORT? - user3741598
@user3741598 只需执行 NSXMLParser* xmlParserObject。我认为在上面的示例代码中,解析器首先在头文件中声明,因此不需要说明其类型。那是我的猜测。 - Max von Hippel
@Nirav,你能否看一下我的问题:http://stackoverflow.com/questions/43539307/how-to-post-string-with-special-character-and-thai-language-using-xml-parsing-in - Muju

3
// This one called out when it hit a starting tag on xml in your case <question>

  BOOL got = FALSE;

  - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 

 {

      if([elementName isEqualToString:@"question"])
       {
         got = TRUE;
       }
}

// This is third one to called out which gives the end tag of xml in your case </question>


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName



// This delegate is the second one to called out which gives the value of current read tag in xml

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
 {

   if(got)
  {
    NSLog(@"your desired tag value %@",string);
    got = FALSE; 
  }
}

2

您需要实现NSXMLParserDelegate的回调函数。

其中关键的回调函数包括:

// called when it found an element - in your example, question or answer
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 

// called when it hits the closing of the element (question or answer)
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

// called when it found the characters in the data of the element
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

因此,当您遇到元素时,可以设置状态,指示解析器当前是否在问题或答案元素中(使用iVar),然后当您通过foundCharacters回调时,根据您在访问元素时设置的状态,您就知道将数据分配给哪个变量(问题或答案)。


2
你需要实现该方法。
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

一旦您看到想要获取其(内部)文本的元素,请在程序中设置一个标志,并保留一个字符串,其中包含foundCharacters在标签之间找到的内容。一旦触发didEndElement方法,您可以对该字符串执行所需操作并重置标志。

例如:

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
  if (sawQuestion) {
    // need to check here that self->myString has been initialized
    [self->myString appendString:string];
 }
}

didEndElement 中,您可以重置标志 sawQuestion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接