我正在尝试解析一个简单的 xml。xml 的结构如下所示:
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
............
............
我的解析代码是:
-(void)parserDidStartDocument:(NSXMLParser *)parser{
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"Element Name is =%@, \nNamespaceURI is =%@, \nQualifiedName is =%@, \n, Attributes Dictionary is = %@",elementName,namespaceURI,qName,attributeDict);
currentEltValue = elementName;
if([elementName isEqualToString:@"status"]){
parsedata = [[NSString alloc ]init];
NSLog(@"Initializing the variable here");
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if([currentEltValue isEqualToString:@"status"]){
NSLog(@"Inside if loop");
parsedata = string;
NSLog(@"Found Characters value is = %@",parsedata);
}
else parsedata = NULL;
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"status"]){
NSLog(@"PARSED DATA: = %@",parsedata);
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"Did end document \t parseData Valus is =%@",parsedata);
}
当我运行程序时,在我的控制台中我得到:
2012-08-01 13:21:10.721 XML_Parsing[5624:207] Element Name is =status,
NamespaceURI is =(null),
QualifiedName is =(null),
, Attributes Dictionary is = {
}
2012-08-01 13:21:10.722 XML_Parsing[5624:207] Initializing the variable here
2012-08-01 13:21:10.722 XML_Parsing[5624:207] Inside if loop
2012-08-01 13:21:10.723 XML_Parsing[5624:207] Found Characters value is = OK
2012-08-01 13:21:10.723 XML_Parsing[5624:207] PARSED DATA: = OK
2012-08-01 13:21:10.724 XML_Parsing[5624:207] Inside if loop
2012-08-01 13:21:10.724 XML_Parsing[5624:207] Found Characters value is =
2012-08-01 13:21:10.803 XML_Parsing[5624:207] Did end document parseData Valus is =(null)
我不知道为什么 if 条件运行两次?
更新 *解决方案* 这解决了我的问题:
1] 在 DidEndElement 中:声明 currentEltValue = @""。
2] 以 self.parsedata 的形式访问所有 parsedata 实例。