【问题标题】:How can i Parse this xml using NSXMLParser in ios?我如何在 ios 中使用 NSXMLParser 解析这个 xml?
【发布时间】:2026-01-10 09:45:02
【问题描述】:
<root>
    <table name="radios">
        <column name="nameradio">Radio1</column>
        <column name="logo">http://app.syndicationradio.fr/demo/logo1.png</column>
        <column name="stream">http://cloud2.syndicationradio.fr:8020</column>
        <column name="twitter">http://www.twitter.com/#syndicationradio</column>
        <column name="facebook">http://www.facebook.com/syndicationradio</column>
        <column name="titre">http://app.syndicationradio.fr/demo/title.xml</column>
    </table>
    <table name="radios">
        <column name="nameradio">Radio2</column>
        <column name="logo">http://app.syndicationradio.fr/demo/logo1.png</column>
        <column name="stream">http://cloud2.syndicationradio.fr:8020</column>
        <column name="twitter">http://www.twitter.com/#syndicationradio</column>
        <column name="facebook">http://www.facebook.com/syndicationradio</column>
        <column name="titre">http://app.syndicationradio.fr/demo/title.xml</column>
    </table>
</root>

现在请有人帮忙找出答案,我如何在 IOS 中使用 NSXMLParser 或任何其他 xml 解析器(假设为 TBXML)从 xml 数据中获取这些 url?

编辑:你也可以给我这个xml的libxml解析器的例子。

提前致谢。

【问题讨论】:

    标签: iphone ios nsxmlparser


    【解决方案1】:

    这就是你可以使用 NSXMLParser 的方式:

    在您的 .h 文件中声明:

    NSMutableData       *webPortFolio;
    NSMutableString     *soapResultsPortFolio;
    NSURLConnection     *conn;
    
    //---xml parsing---
    
    NSXMLParser         *xmlParserPortFolio;
    BOOL                elementFoundPortFolio;
    NSMutableURLRequest *req;
    
    NSString            *theXMLPortFolio;
    NSString            *strSoapMsg;
    UIAlertView         *alertView;
    

    在您的 .m 文件中使用以下代码:

    -(void)callURL
    {
    
         //Your logic to call URL.
    
         conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
         if (conn)
         {
             webPortFolio = [[NSMutableData data] retain];
         }
    }
    And to handle the response you can use following functions :
    
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        [webPortFolio setLength:0];     
    }
    
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [webPortFolio appendData:data];
    }
    
    -(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
    {
    
        NSLog(@"error...................%@",[error description]);
        [webPortFolio release];
        [connection release];
    }
    
    -(void) connectionDidFinishLoading:(NSURLConnection *) connection
    {
    
        //Check the request and returns the response.
    
        NSLog(@"DONE. Received Bytes: %d", [webPortFolio length]);
    
        theXMLPortFolio = [[NSString alloc] 
                          initWithBytes: [webPortFolio mutableBytes] 
                          length:[webPortFolio length] 
                          encoding:NSUTF8StringEncoding];
    
        //---shows the XML---
    
        NSLog(@"shows the XML %@",theXMLPortFolio);
        [theXMLPortFolio release];    
    
        if(xmlParserPortFolio)
        {
            [xmlParserPortFolio release];
        }
        xmlParserPortFolio = [[NSXMLParser alloc] initWithData: webPortFolio];
        [xmlParserPortFolio setDelegate: self];
        [xmlParserPortFolio setShouldResolveExternalEntities:YES];
        [xmlParserPortFolio parse];
        [webPortFolio release];
        [connection release];
    }
    
    //---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:@"your_tag_name"])
        {
            if (!soapResultsPortFolio)
            {
                soapResultsPortFolio = [[NSMutableString alloc] init];
            }
            elementFoundPortFolio = TRUE;
            NSLog(@"Registration...%@",soapResultsPortFolio);
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {
            elementFoundPortFolio = TRUE;
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {
            elementFoundPortFolio = TRUE;
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {
            elementFoundPortFolio = TRUE;
        }
    
    }
    
    -(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
    {
        if (elementFoundPortFolio)
        {
            [soapResultsPortFolio appendString: string];
        }      
    }
    
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
    {
        NSLog(@"Parser error %@ ",[parseError description]);
    }
    
    
    //---when the end of element is found---
    -(void)parser:(NSXMLParser *)parser 
    didEndElement:(NSString *)elementName 
     namespaceURI:(NSString *)namespaceURI 
    qualifiedName:(NSString *)qName
    {
        if ([elementName isEqualToString:@"your_tag_name"])
        {          
            NSLog(@"display the soap results%@",soapResultsPortFolio);
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {          
            //Perform required action
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {
            //Perform required action
        }
        else if([elementName isEqualToString:@"your_tag_name"])
        {
            //Perform required action
        }
    
        [soapResultsPortFolio setString:@""];
        elementFoundPortFolio = FALSE;
    }
    

    【讨论】:

      【解决方案2】:

      好的,您要求提供libxml 示例。我在一个项目中使用了它,但使用TBXML 而不是NSXMLParser,因为这会导致编码和数据检索的重要问题。

      首先,您必须从网上下载TBXML.mTBXML.h 文件并将它们导入到您的项目中。然后,您还必须在 Link Binary with Libraries 中将 libxml2.dylib 链接到您的项目。

      完成此操作后,您必须执行此操作以检索数据(基于您的 XML 源):

      NSData *xmlData = [NSData dataWithContentsOfURL:yourURL];
      TBXML *tbxml = [TBXML newTBXMLWithXMLData:data error:nil];
      [self getData:tbxml.rootXMLElement];
      
      - (void) getData : (TBXMLElement *) element
      {
          do {
              if([[TBXML elementName:element] isEqualToString:@"table"])
              {
                  if([[TBXML elementName:element] isEqualToString:@"column"])
                  { 
                      if([[TBXML attributeName:element] isEqualToString:@"nameradio"])
                      {
                          // You decide what to do here
                      }
                  }
              }
              if (element->firstChild) [self getData:element->firstChild];
          } while(element = element->nextSibling);
      }
      

      您可能需要更改此代码,但这里有您需要的所有基本内容。

      【讨论】:

      • 谢谢。你提供的代码非常好和清晰。你能给我TBXML.h和TBXML.m的链接吗?因为我已经下载了一个,但它显示了一些错误。
      • 很高兴 ;) Here 你会找到头文件,here 是代码文件。这是 1.5 版,我使用过的版本,对我来说效果很好。
      • 很抱歉,但这里的另一个问题是 `if([[TBXML attributeName:element] isEqualToString:@"nameradio"])` 显示一些类似 incompatible pointer type TBXMLElement* 的警告
      • 非常感谢您的帮助,但我认为我想要的答案是我接受的答案。再次感谢。
      【解决方案3】:

      试试这个:

      - (void)viewDidLoad {
          [super viewDidLoad];
      
          NSURL *url = [[NSURL alloc] initWithString:@"yourURL"];
          NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
          [parser setDelegate:self];
          BOOL result = [parser parse];
          // Do whatever with the result
      }
                     
      - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
          NSLog(@"Did start element");
          if ([elementName isEqualToString:@"root"]) {
              NSLog(@"found rootElement");
              return;
          }
      }
              
      - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
          NSLog(@"Did end element");
          if ([elementName isEqualToString:@"root"]) {
              NSLog(@"rootelement end");
          }           
      }
      
      - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
          NSString *tagName = @"column";
          if ([tagName isEqualToString:@"column"]) {
              NSLog(@"Value %@",string);
          }
      }
      

      【讨论】:

      • 我有一个字符串,不是 url: NSString *urlString = [NSString stringWithFormat:@"somewebsite.com/RunPHPtoOutputXML.php?id=%d", ii]; //ii 是一个整数,然后我运行以下命令并获取 XML: NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:urlString]]; NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returnedResponse:&response error:&error];
      • @user3741598 你到底想问什么?
      • 我被切断了 - 字符太多 - 将打开一个新问题。虽然我只是想出了一个可能的快速、肮脏的工作答案,我回家后会尝试。感谢您的提问。