0

我是iphone开发新手,对解析不太了解。但是我尝试了以下代码来获取距离元素文本。我正在做以下链接的 XML 解析:

http://maps.googleapis.com/maps/api/directions/xml?origin=30.9165904,75.8634752&destination=30.89314000,75.86938000&sensor=true

请检查我尝试过的代码:

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

 currentElement = [elementName copy];
if([currentElement isEqualToString:@"distance"])


{
       NSLog(@"ENTER IN distance");
      text = [[NSMutableString alloc]init];

  {
       dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:text,@"text",nil];
  }

    }

}


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
  {
      if ([currentElement isEqualToString:@"text"])
     {
        [dictionary setObject:text forKey:currentElement];
        [text appendString:string];
        NSLog(@"text....%@",text);
     }
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:  
 (NSString *)namespaceURI qualifiedName:(NSString *)qName

{

 if ([elementName isEqualToString:@"distance"])
{
    [distanparsingarray addObject:dictionary];

}

}

  By using above method I am getting the text both of distance and duration. But I want only distance text. Please tell me what I am doing wrong in above code.

提前致谢。

4

1 回答 1

0

您必须通过以下方式对其进行管理。在类级别添加 BOOL 变量。当您将 currentElement 标识为距离时设置它。仅当上述 BOOL 为真时,内部找到的字符才会将字符串附加到文本。当 currentElement 不等于距离时,在 didEndElement 中将此 BOOL 设为 false。

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:
(NSDictionary *)attributeDict
{ 
     currentElement = [elementName copy];
     if([currentElement isEqualToString:@"distance"])
     {
         flag = TRUE; //created at class level.
         NSLog(@"ENTER IN distance");
         text = [[NSMutableString alloc]init];    
         {
              dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:text,@"text",nil];
         }    
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
     if ([currentElement isEqualToString:@"text"] && flag == TRUE)
     {
        [dictionary setObject:text forKey:currentElement];
        [text appendString:string];
        NSLog(@"text....%@",text);
     }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:  
 (NSString *)namespaceURI qualifiedName:(NSString *)qName
{  
     if ([elementName isEqualToString:@"distance"])
     {
         [distanparsingarray addObject:dictionary];
         flag = FALSE;
     }
}
于 2012-06-25T11:37:54.430 回答