iosobjective-cnsstringnsscanner

Get substring from xml string objective-c


I know this question has been asked many times. I've response string that contains xml.

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

For each request i receive new short xml string, and i need to get value in "response" node. How i can do this, without creating xml parser? I don't want to create xml parser for this short xml.


Solution

  • You could use NSScanner and scan from <response> up to </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);