如何将NSXMLParser用于具有相同名称的解析器

时间:2013-01-08 15:16:39

标签: nsxmlparser

这是我的xml代码:

<root><article>
   <title>Test media</title>
   <media>
     <thumbnail>thumbnail1.png</thumbnail>
     <full>full1.png</full>
     <title>thumb1</title>
  </media>
  <media>
     <thumbnail>thumbnail2.png</thumbnail>
     <full>full2.png</full>
     <title>thumb2</title>
  </media>
  <media>
     <thumbnail>thumbnail3.png</thumbnail>
     <full>full3.png</full>
     <title>thumb3</title>
  </media></article></root>

如何获取媒体节点和标题的所有信息(缩略图,标题,标题)。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用以下NSXMLParser类方法。当您获得标签的开头和结尾时,您可以按照您的需要放置您的逻辑。

/---when the start of an element is found---
-(void)  parser:(NSXMLParser *) parser 
 didStartElement:(NSString *) elementName 
 namespaceURI:(NSString *) namespaceURI 
 qualifiedName:(NSString *) qName
 attributes:(NSDictionary *) attributeDict
{
    if( [elementName isEqualToString:@"media"])
    {
        if (!soapResultsPortFolio)
        {
            soapResultsPortFolio = [[NSMutableString alloc] init];
        }
        elementFoundPortFolio = TRUE;
        NSLog(@"Registration...%@",soapResultsPortFolio);
    }
    else if([elementName isEqualToString:@"thumbnail"])
    {
        elementFoundPortFolio = TRUE;
    }
    else if([elementName isEqualToString:@"full"])
    {
        elementFoundPortFolio = TRUE;
    }
    else if([elementName isEqualToString:@"title"])
    {
        elementFoundPortFolio = TRUE;
    }

}


 //---when the end of element is found---
-(void)parser:(NSXMLParser *)parser 
didEndElement:(NSString *)elementName 
 namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"media"])
    {          
        NSLog(@"display the soap results%@",soapResultsPortFolio);
    }
    else if([elementName isEqualToString:@"thumbnail"])
    {          
        //Perform required action
    }
    else if([elementName isEqualToString:@"full"])
    {
        //Perform required action
    }
    else if([elementName isEqualToString:@"title"])
    {
        //Perform required action
    }

    [soapResultsPortFolio setString:@""];
    elementFoundPortFolio = FALSE;
}