Analizar datos XML a NSMutableArray iOS – iPhone

Esta es la información 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> 

Aquí quiero get los valores <categoryName> en mi NSMutableArray categList .

El código que he usado es:

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

Pero no estoy obteniendo los nombres de categoría en mi NSMutableArray categList :

¿Qué ocurre en mi código? Significado de la palabra

Gracias

Oye Puedes usar XMLReader pero devolverá NSDictionary .

La siguiente demostración de código para XMLReader to get NSDictionary .

Importar XMLReader en su file.

 #import "XMLReader.h" 

Luego usa el siguiente método para get NSDictionary . Donde tienes que pasar tu XML como NSString .

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

Si desea utilizar GDataXMLParser puede usar el siguiente código que funciona bien

Primer file de biblioteca Impost GDataXMLParser, luego escriba 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]; } 

aquí tengo el análisis de ti. La aplicación funciona muy bien, por favor comtesting que haga una class de orientación de object de categoría y la uses.

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

y llame a la function loaddatafrm xml como [self loaddatafromxml]; Está funcionando bien, pruébalo.

Gracias

Utiliza if ( [elementName isEqualToString:@"categList"])... pero no puedo encontrar el nombre de categList en tu muestra XML. Comtesting por favor, esto puede ser un problema.