从xml字符串objective-c获取子字符串

时间:2011-08-29 08:16:06

标签: ios objective-c nsstring nsscanner

我知道这个问题已被多次询问过。我的响应字符串包含xml。

<?xml version="1.0" encoding="utf-8"?>
<response>116363111</response>

对于每个请求,我收到新的短xml字符串,我需要在“response”节点中获取值。如何在不创建xml解析器的情况下做到这一点?我不想为这个简短的xml创建xml解析器。

1 个答案:

答案 0 :(得分:3)

您可以使用NSScanner并从<response>扫描到</response>

NSString *xmlString = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response>116363111</response>";

NSString *startTag = @"<response>";
NSString *endTag = @"</response>";
NSString *responseString;

NSScanner *scanner = [[NSScanner alloc] initWithString:xmlString];
[scanner scanUpToString:startTag intoString:nil];
scanner.scanLocation += [startTag length];
[scanner scanUpToString:endTag intoString:&responseString];
[scanner release];

NSLog(@"Response string is %@", responseString);