Parsing an XML file with NSXMLParser - getting values

I have an XML file containing some data that I would like to use:

<?xml version="1.0" encoding="UTF-8" ?> <items> <item name="product" price="19.95" where="store"> This is the first product. </item> <item name="product2" price="39.95" where="online"> This is the second product. </item> <item name="product3" price="99.95" where="garagesale"> This is the third product. </item> </items> 

If I made 4 arrays, one for the name, one for the price, one for where it was purchased, and one for its description, how will I get the data into arrays?

I decided to use NSXMLParser but could not get name , price , where or description.

I was fixated on how to do this.

Any help was appreciated.

+7
source share
4 answers

First you need to create an object that does parsing. It will install an instance of NSXMLParser , configure itself as a delegate for the parser, and then invoke the parsing message. He may also be responsible for storing your four arrays of results:

 NSXMLParser * parser = [[NSXMLParser alloc] initWithData:_data]; [parser setDelegate:self]; BOOL result = [parser parse]; 

The message that is most interested in the implementation in your delegate objects was didStartElement . This guy gets a call for every element of your XML file. In this callback, you can add your name, price, and attributes to their respective arrays.

 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { // just do this for item elements if(![elementName isEqual:@"item"]) return; // then you just need to grab each of your attributes NSString * name = [attributeDict objectForKey:@"name"]; // ... get the other attributes // when we have our various attributes, you can add them to your arrays [m_NameArray addObject:name]; // ... same for the other arrays } 
+15
source

in the next method

 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if([elementName isEqualToString:@"item"]) { NSString *name=[attributeDict objectForKey:@"name"]; NSString *price=[attributeDict objectForKey:@"price"]; NSString *where=[attributeDict objectForKey:@"where"]; } } 
+3
source

To get the value between the tags (for example, β€œThis is the first product.”), You can override - (void) the parser: (NSXMLParser *) the parser foundCharacters: (NSString *) string

+3
source

you should consider the element tag dictionary as an array and three tags (name, price and where) as an object in the index 0,1,2

0
source

All Articles