问题
I have an xml file with a parent child structure such as :
<geometry id="001-mesh" name="001">
<mesh>
<source id="001-mesh-positions">
<float_array id="001-mesh-positions-array" count="228">
I am able to parse the data successfully using NSXMLParser. However the problem is I want to store the child information in relation to the parent - for example when a geometry id is detected, I then want to store the associated source id and float_array id.
Can anyone suggest a way I could this ? The below code will detect when a given element is found during parsing, but I'm not sure how to then store the values.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
// NSLog(@"Parse Started");
//NSLog(@"Element Name is %@", elementName);
if([elementName isEqualToString:@"geometry"]) {
NSLog(@"Object Detected");
NSString *name = [attributeDict objectForKey:@"name"];
NSLog(@"Name is %@",name);
}
if ([elementName isEqualToString:@"float_array"]) {
NSLog(@"Vertices Detected");
NSString * vertices = [attributeDict objectForKey:@"count"];
NSLog(@"Vertices are %@", vertices);
}
}
回答1:
At the time when the parser detects the geometry
tag, the source id and float_array id are not available: they have not been parsed yet. The usual trick is to wait for the child element, and do the processing when it becomes available. You can do it by creating a new Geometry
object (or whatever corresponds to XML's geometry
tag in your model), and make it available to the didStartElement:...:
method, for example by setting it into an ivar called myGeometry
. Once you detect float_array
element, parse its id
, and call
[myGeometry setId:floatArrayId];
回答2:
Use either the class variable or the global variable to hold the current values of geometry id ..
来源:https://stackoverflow.com/questions/9278633/nsxmlparser-capturing-parent-and-child-information-iphone