0

我正在解析 XML 响应并将其添加到 NSMutableArray。问题是 XML 响应的最后一个值没有被添加到 NSMutableArray 中。无法找到我哪里出错了?我的 XML 文件如下所示:

<IDList>
   <Employee>
      <ID>1</ID>
   </Employee
   <Employee>
      <ID>2</ID>
   </Employee>
   <Employee>
      <ID>3</ID>
   </Employee>
   <Employee>
      <ID>4</ID>
   </Employee>
</IDList>

我为解析编写的代码是:

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



 if([elementName isEqualToString:@"IDList"])
 {
 arr1=[[NSMutableArray alloc] init];
 drr1=[[NSMutableDictionary alloc] init];

 }
 if([elementName isEqualToString:@"Employee"])
 { 
 drr1=[[NSMutableDictionary alloc] init];        
 }
 srr1=[[NSMutableString alloc] init];

 } 


 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{


 [srr1 appendString:string];
 }


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

 if([elementName isEqualToString:@"ID"])
 {

 [drr1 setObject:srr1 forKey:@"ID"];
 [srr1 release],srr1=nil;
 return;
 }  

 if([elementName isEqualToString:@"Employee"]) 
 { 
 [arr1 addObject:drr1]; 
 }    


 if([elementName isEqualToString:@"IDList"])
 {

 [drr1 release];

 }

 [srr1 release],srr1=nil;

 }

我在 arr1 中看到的结果是:

 (
    {
      ID="1",
    }
    {
      ID="2",
    }
    {
      ID="3",
    }
    {
      ID="",
    }
    )

我看不到最后一个值。我怎样才能得到所有的项目?

4

1 回答 1

0

我不知道它是否会解决任何问题,但这是我会做的:

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

    if ([elementName isEqualToString:@"IDList"]) {        
         arr1=[[NSMutableArray alloc] init];
    }
    else if ([elementName isEqualToString:@"Employee"]) { 
        drr1=[[NSMutableDictionary alloc] init];
        [arr1 addObject:drr1]; 
    }
    else if ([elementName isEqualToString:@"ID"]) {
        srr1=[[NSMutableString alloc] init];
    }
 } 

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

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

    if ([elementName isEqualToString:@"ID"]) {
        [drr1 setObject:srr1 forKey:@"ID"];
        [srr1 release],srr1=nil;
        return;
    }  
    else if ([elementName isEqualToString:@"Employee"]) { 
        [drr1 release];
        drr1 = nil; 
    }
}
于 2012-10-14T05:54:28.053 回答