xcode 在 NSXMLParser 中解析 xml

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8813968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:57:57  来源:igfitidea点击:

Parsing xml in NSXMLParser

objective-ciosxcodexml-parsingnsxmlparser

提问by blake305

I have read many examples of how to get text out of xml files, but just don't get how to. Here is a sample xml file:

我已经阅读了许多关于如何从 xml 文件中获取文本的示例,但就是不知道如何操作。这是一个示例 xml 文件:

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

Using -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI, what's the easiest way to get the values Questionand Answer? I already have my parser delegate hooked up and all that blah.

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI,有什么获得的值最简单的方法QuestionAnswer?我已经连接了我的解析器委托等等。

回答by Nirav

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

要实现 NSXMLParser,您需要实现它的委托方法。

First of all initiate NSXMLParser in this manner.

首先以这种方式启动 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;
}

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

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

回答by superGokuN

// 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; 
  }
}

回答by bryanmac

You have to implement the callbacks for NSXMLParserDelegate

您必须为NSXMLParserDelegate实现回调

The key ones are:

关键是:

// 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

So, when you hit the elements, you can set state whether the parser is currently in the question or answer element (with an iVar) and then when you get called back with foundCharacters, based on the state you set when you hit the element, you know which variable (question or answer) to assign the data to.

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

回答by ddodev

You need to implement the method

您需要实现该方法

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

Once you see the elements whose (inner)text you want to grab, set a flag in your program, and keep a string with the things that foundCharactersfinds between the tags. Once you hit the didEndElementmethod, you can do what you want with the string and reset the flag.

一旦您看到要抓取其(内部)文本的元素,请在您的程序中设置一个标志,并保留一个字符串,其中包含foundCharacters在标签之间找到的内容。一旦你点击了这个didEndElement方法,你就可以对字符串做你想做的事情并重置标志。

For example

例如

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

and in didEndElementyou can reset the flag sawQuestion

并且在didEndElement您可以重置标志sawQuestion