2012-01-16 65 views
0

解析我有這樣一個XML文件:用的NSXMLParser

<name>Alberto</name> 
<subname>Martín</subname> 
<age>24</age> 

我想的NSXMLParser解析器,並將其保存數據:

NSString *name; 
NSString *subname; 
NSString *age; 

要做到這一點即時通訊使用:

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

if([elementName isEqualToString:@"name"]) 
{ 
    if (!soapResults) 
    { 
     soapResults = [[NSMutableString alloc] init]; 

} 

    elementoEncontrado = YES; 
}} 

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

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

if ([elementName isEqualToString:@"name"]) 
{ 
    name=soapResults; 
} 
if ([elementName isEqualToString:@"subname"]) 
{ 
    subname=soapResults; 
} 
    if ([elementName isEqualToString:@"age"]) 
{ 
    age=soapResults; 
} 


NSLog(@"%@", name, subname, age); 

問題是子名和年齡從不出現...

+0

所有這些線來分析一個非常簡單的XML?爲什麼不使用一個叫做TBXML的簡單庫(http://tbxml.co.uk) – Saurabh 2012-01-16 17:53:53

回答

1

您應該檢查這裏的所有元素,因爲您只爲name元素創建NSMutableString。

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

    if([elementName isEqualToString:@"name"]) 
    { 
     if (!soapResults) 
     { 
      soapResults = [[NSMutableString alloc] init]; 
     } 

     elementoEncontrado = YES; 
    } 
} 

和發佈/零您soapResults這裏,以及設置你的elementoEncontradoNO這裏

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

    if ([elementName isEqualToString:@"name"]) 
    { 
     // copy or retain this, unless ARC. 
     name=soapResults; 
    } 

    if ([elementName isEqualToString:@"subname"]) 
    { 
     subname=soapResults; 
    } 

    if ([elementName isEqualToString:@"age"]) 
    { 
     age=soapResults; 
    } 
    NSLog(@"%@", name, subname, age); 
    [soapResults release]; 
    soapResults = nil; 

    elementoEncontrado = NO; 
} 
+0

好的朋友,謝謝。將NSString複製到另一個,這是這種情況下最好的形式? name = [copy soapResults]或[name release] name = [NSString stringWthString:theName] ???或其他形式? – 2012-01-16 21:01:45

+0

我認爲這個名字= [soapResults copy];應該工作得很好。同樣,如果不在ARC下,請記住稍後再發布這些實例。 – 2012-01-16 21:11:36