2012-05-02 74 views
0

我有一個簡單的XML文件。我只想獲取用戶名和密碼。但是當我使用nslog觀察結果時,它會產生重複的值。 XML結構僅是這樣的:使用NSXmlParser解析XML文件時獲取重複值

<Login xmlns="http://tempuri.org/"> 
    <userName>Vincent</userName> 
    <password>string</password> 
    <status>OK</status> 
</Login> 



- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{ 
    if ([elementName isEqualToString:@"userName"]) { 
     NSLog(@"Node is found correctly"); 
    } 
} 


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{ 
    if (!userNameString) { 
     userNameString=[[NSMutableString alloc]init]; 
    } 
    [userNameString appendString:string]; 
    NSLog(@"%@",userNameString); 
} 


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError 
{ 
    NSInteger errorCode=[parseError code]; 
// NSLog(@"%d,%@",errorCode,[parseError localizedDescription]); 
} 


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{ 
    if ([elementName isEqualToString:@"userName"]) { 
     userNameString=nil; 
    } 
} 

這裏是將其通過的NSLog生成的結果:

2012-05-02 19:47:27.620 DeliveryManagement [4364:11003]

Vincent 

2012-05-02 19:47:27.620 DeliveryManagement [4364:11003]

2012-05-02 19:47:27.621 DeliveryManagement [4364:11003] string 2012-05-02 19:47:27.622 DeliveryManagement [4364:11003] 串

2012-05-02 19:47:27.623 DeliveryManagement [4364:11003] 串 行 2012-05-02 19 :47:27.623 DeliveryManagement [4364:11003] 串 行

2012-05-02 19:47:27.624 DeliveryManagement [4364:11003] 串 行

2012-05-02 19時47分:27.625 DeliveryManagement [4364:11003] st環 行

2012-05-02 19:47:27.626 DeliveryManagement [4364:11003] 串 行

2012-05-02 19:47:27.626 DeliveryManagement [4364:11003] 串 行

2012-05-02 19:47:27.627 DeliveryManagement [4364:11003] 串 行

2012-05-02 19:47:27.628 DeliveryManagement [4364:11003]節點被正確地發現 2012-05-02 19:47:27.642 DeliveryManagement [4364:11003] 串 OK

+0

在任何人能夠幫助你之前,你需要顯示解析XML文檔的代碼。 – jonkroll

+0

對不起,我粘貼了XML解析器的編碼。 –

回答

0
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{ 
if ([elementName isEqualToString:@"userName"]) { 
    NSLog(@"Node is found correctly"); 
    if(userNameString == nil) 
     userNameString = [NSMutableString string]; 
    else 
     [userNameString setString:@""]; 
} 
else { 
    userNameString = nil; 
} 

} 


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

[userNameString appendString:string]; 
if (userNameString) 
{ 
    userNameString = nil; 
} 
NSLog(@"%@",userNameString); 
} 

只需添加以下代碼,它應該工作。 基本上重複的值是因爲每個值之後的'\ n'字符。所以我們需要讓userNameString = nil;追加後。這樣它進入

  • (無效)解析器:(*的NSXMLParser)分析器foundCharacters:(的NSString *)字符串

但其零所以沒有價值附加。希望它可以幫助你..

+0

plz讓我知道如果它爲你工作... thnx –