how to parse xml for ios development

2019-02-14 18:54发布

问题:

So I know how to parse some XML structures but I am currently trying to parse this specific xml structure thats a bit different to what I am used to.

normally I would parse something like

<xml>
  <data>
    <name>Forrest</name>
    <age>25</name>
    <username>forrestgrant</username>
  </data>
</xml>

But now I'm working with some xml like so..

<xml>
  <data name="Forrest" age="25" username="forrestgrant" />
  <other value="6" />
</xml>

how do I access those variables when they are structured like this? This is how I would normally approach this task, which is baised of searching for the title tags and getting the data from each one.. however I am now trying to figure out how to parse this other style of xml.

- (void)startTheParsingProcess:(NSData *)parserData
{
    [myDataArray release]; // clears array for next time it is used.
    myDataArray = [[NSMutableArray alloc] init]; //initalizes the array

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //incoming parserDatapassed to NSXMLParser delegate which starts parsing process 

    [parser setDelegate:self];
    [parser parse]; //Starts the event-driven parsing operation.
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqual:@"item"]) {
        // NSLog(@"Found title!");
        itemString = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [itemString appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqual:@"item"]) {
        //NSLog(@"ended title: %@", itemString);
        [myDataArray addObject:itemString]; //this is where i pass the values over to my array.

        [itemString release];
        itemString = nil;
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    // Passes myDataArray to the method that will sort and display the array into a uitableview.
    [self startSortingTheArray:myDataArray];
}

any help would be greatly appreciated..

回答1:

The xml data above provides the data as attributes on the xml element.

This callback method gives you access to the attributes as a dictionary of key values (attributeDict).

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

NSLog the dictionary out in that method to see the values:

NSLog(@"attributes: %@", attributeDict);


回答2:

In your didStartItem: method, the attributes dictionary will contain values for all the XML attributes.