我如何在 ios 中使用 NSXMLParser 解析这个 xml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15172669/
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-08-30 22:32:10  来源:igfitidea点击:

How can i Parse this xml using NSXMLParser in ios?

iphoneiosnsxmlparser

提问by Emon

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

Now please is there anybody help to find out that, how can i get those url from the xml data using NSXMLParseror any other xml parser suppose TBXMLin IOS?

现在请有没有人帮忙找出来,我怎样才能从 xml 数据中获取这些 url 使用NSXMLParser或任何其他 xml 解析器假设TBXML在 IOS 中?

Edit: you can also give me example of libxmlparser for this xml.

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

Thanks In Advance.

提前致谢。

回答by Dharmbir Singh

Try to this one

试试这个

    - (void)viewDidLoad

   {
      NSURL *url = [[NSURL alloc]initWithString:@"yourURL"];
        NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
        [parser setDelegate:self];
       BOOL result = [parser parse];
   }

    - (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);
      }

    }

回答by Rob

Ok you asked for a libxmlexample. I used it in a project but with TBXMLinstead of NSXMLParserbecause this one caused important problems of encoding and data retrieving.

好的,你问了一个libxml例子。我在一个项目中使用它TBXML而不是NSXMLParser因为它导致了编码和数据检索的重要问题。

First you have to download TBXML.mand TBXML.hfiles from the web and import them into your project. Then you also have to link libxml2.dylibto your project in Link Binary with Libraries.

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

Once this done, you will have to do this to retrieve your data (based on your XML source) :

完成此操作后,您将必须执行此操作以检索您的数据(基于您的 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);
}

You probably will have to change this code but here you have all the basic things you need.

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

回答by Rushi

This is how you can use NSXMLParser :

这是如何使用 NSXMLParser :

In your .h file declare :

在您的 .h 文件中声明:

NSMutableData       *webPortFolio;
NSMutableString     *soapResultsPortFolio;
NSURLConnection     *conn;

//---xml parsing---

NSXMLParser         *xmlParserPortFolio;
BOOL                elementFoundPortFolio;
NSMutableURLRequest *req;

NSString            *theXMLPortFolio;
NSString            *strSoapMsg;
UIAlertView         *alertView;

In your .m file use the following code:

在您的 .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;
}