0

我有一个简单的 XML 文件。我只想获取用户名和密码。但是当我使用 nslog 观察结果时,它会产生重复值。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 交付管理[4364:11003]

  Vincent

2012-05-02 19:47:27.620 交付管理[4364:11003]

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

2012-05-02 19:47:27.623 DeliveryManagement[4364:11003] 字符串 OK 2012-05-02 19:47:27.623 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.624 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.625 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.626 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.626 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.627 DeliveryManagement[4364:11003] 字符串 OK

2012-05-02 19:47:27.628 DeliveryManagement[4364:11003] 正确找到节点 2012-05-02 19:47:27.642 DeliveryManagement[4364:11003] 字符串 OK

4

1 回答 1

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; 附加后。这样它进入

  • (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

但它的 nil 所以没有附加值。希望对你有帮助。。

于 2012-05-02T10:15:16.293 回答