将XML解析数据添加到iPhone中的NSMutableArray?

时间:2012-10-12 06:14:16

标签: objective-c xcode4 xml-parsing nsmutablearray

我正在解析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="",
    }
    )

我看不到最后一个值。我怎样才能得到所有物品?

1 个答案:

答案 0 :(得分: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; 
    }
}