xcode 将 XML 数据解析为 NSMutableArray iOS - iPhone

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

Parsing XML data to NSMutableArray iOS - iPhone

iphoneobjective-ciosxcodexcode4.2

提问by Omer Waqas Khan

This is the XML data:

这是 XML 数据:

<Categorys> 
    <Category>  
        <categoryId>25</categoryId>  
            <categoryName>My Photos</categoryName>                                  
                <categoryDescription>Description</categoryDescription>      
            <categoryIconPath>7.jpg</categoryIconPath>      
            <userId>2</userId>  
            <categoryStatus>ON</categoryStatus>  
        <publicPrivate>Private</publicPrivate>
    </Category>
......more categories
<Categorys>

Here I want to get the <categoryName>values into my NSMutableArray categList.

在这里,我想将<categoryName>值放入我的NSMutableArray categList.

The code I have used is:

我使用的代码是:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
                                       qualifiedName:(NSString *)qualifiedName 
                                          attributes:(NSDictionary*)attributeDict {

    if ( [elementName isEqualToString:@"categList"]) {
        // addresses is an NSMutableArray instance variable
        if (!categList)
            categList = [[NSMutableArray alloc] init];
        return;
    }

    NSLog(@"StartedElement %@", elementName);

    element = [NSMutableString string];

}


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

    if(element == nil)

        element = [[NSMutableString alloc] init];

        [element appendString:string];

}

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

    NSLog(@"Found an element named: %@ with a value of: %@", elementName, element);

    if ([elementName isEqualToString:@"categoryName"]) {

        NSLog(@"\n\n\nfound::::::::::::::: %@", element);

        category = element;

        NSLog(@"category:::: %@", category);

    }

    [categList addObject:element];
    NSLog(@"categList*************** %@", categList);
}

But I am not getting the category names in my NSMutableArray categList:

但是我没有在我的NSMutableArray categList:

Whats wrong in my code? :(

我的代码有什么问题?:(

Thanks

谢谢

回答by Devang

Hey You can use XMLReaderbut it will return NSDictionary.

嘿您可以使用XMLReader但它会返回NSDictionary.

The Following code demo for XMLReader to get NSDictionary.

以下代码演示用于XMLReader to get NSDictionary.

import XMLReaderin your file.

导入XMLReader到您的文件中。

#import "XMLReader.h"

Then use following method to get NSDictionary. Where you have to pass your XMLas NSString.

然后用下面的方法得到NSDictionary。你必须通过你的XMLas 的地方NSString

NSDictionary* xmlDict = [XMLReader dictionaryForXMLString:theXML error:&er];

回答by parag

here i have parsing of you r Application its working very fine pls check it make a category object orientation class and use it.

在这里,我解析了你的应用程序,它的工作非常好,请检查它是否创建了一个面向对象的类别类并使用它。

 -(void)loaddatafromxml
  {
    NSString *ur=[NSString stringWithFormat:@"Enter your url"]; 

     NSURL *url=[NSURL URLWithString:ur];
     NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
     conn=[[NSURLConnection alloc]initWithRequest:req delegate:self];
     if(conn)
     webdata=[[NSMutableData data]retain];
  }

 -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
[webdata appendData:data];
  }
 -(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  {
[webdata setLength:0];  
   }

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
categaryArry=[[NSMutableArray alloc]init];


  NSString *thexml=[[NSString alloc] initWithBytes:[webdata mutableBytes] length:[webdata length] encoding:NSASCIIStringEncoding];

  NSArray *arr=[thexml componentsSeparatedByString:@"<Category>"];


for(int i=1;i<[arr count];i++)
{
    categList *object = [[categList alloc] init];
    NSString *str=[arr objectAtIndex:i];


    NSArray *arr=[str componentsSeparatedByString:@"<categoryId>"];
    NSString *data=[arr objectAtIndex:1];
    NSRange ranfrom=[data rangeOfString:@"</categoryId>"];
    object.catid=[data substringToIndex:ranfrom.location];





    arr=[str componentsSeparatedByString:@"<categoryName>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</categoryName>"];
   object.catname=[data substringToIndex:ranfrom.location];



    arr=[str componentsSeparatedByString:@"<categoryDescription>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</categoryDescription>"];
   object.catdesc=[data substringToIndex:ranfrom.location];






    arr=[str componentsSeparatedByString:@"<categoryIconPath>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</categoryIconPath>"];
    object.caticon=[data substringToIndex:ranfrom.location];





    arr=[str componentsSeparatedByString:@"<userId>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</userId>"];
    object.userid=[data substringToIndex:ranfrom.location];





    arr=[str componentsSeparatedByString:@"<categoryStatus>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</categoryStatus>"];
    object.catstatus=[data substringToIndex:ranfrom.location];





    arr=[str componentsSeparatedByString:@"<publicPrivate>"];
    data=[arr objectAtIndex:1];
    ranfrom=[data rangeOfString:@"</publicPrivate>"];
    object.publicpriv=[data substringToIndex:ranfrom.location];


    [categaryArry addObject:object];
}   

[self.table_data reloadData];

[thexml release];

[connection release];

 }

and call the loaddatafrm xml function as [self loaddatafromxml]; its working nice try it .

并将 loaddatafrm xml 函数调用为 [self loaddatafromxml]; 它的工作很好试试吧。

Thanks

谢谢

回答by iDhaval

If you want to use GDataXMLParser you can use following code that is working fine

如果您想使用 GDataXMLParser,您可以使用以下工作正常的代码

First Impost GDataXMLParser library file then write vbe

首先Impost GDataXMLParser 库文件然后编写vbe

 -(void)XMLParsing
 {

      GdataParser *parser = [[GdataParser alloc] init];

      NSString* urlString = @"YOURURL"; 

      NSURL *url = [[NSURL alloc] initWithString:urlString];

      [parser downloadAndParse:url withRootTag:@"Category" withTags:[NSDictionary dictionaryWithObjectsAndKeys:@"categoryId",@"categoryId",@"categoryName",@"categoryName",@"categoryDescription",@"categoryDescription",@"categoryIconPath",@"categoryIconPath",@"userId",@"userId",@"categoryStatus",@"categoryStatus",@"publicPrivate",@"publicPrivate",nil] 
                         sel:@selector(finishGetDataSF:) 
                  andHandler:self];
      [urlSR release];
      [parser release];
  } 


  -(void)getDate:(NSDictionary*)dict
  {
      NSLog(@"Data from XML file  ==  %@",dict);

      NSArray* arrayTemp = [dict copy];
  }

回答by SVGreg

You use if ( [elementName isEqualToString:@"categList"])...but I can't find categListname in you XML sample. Check please - this can be an issue.

您使用if ( [elementName isEqualToString:@"categList"])...但我categList在您的 XML 示例中找不到名称。请检查 - 这可能是一个问题。