Best approach for XML parsing on the iPhone

前端 未结 3 602
终归单人心
终归单人心 2020-12-02 17:46

I\'ve familiarized myself with the NSXMLParser from the iPhone SDK but I find the event-driven nature of it awkward for my purposes. I just want to extract some element valu

3条回答
  •  醉梦人生
    2020-12-02 18:27

    Consider the following code snippet, that uses libxml2, Matt Gallagher's libxml2 wrappers and Ben Copsey's ASIHTTPRequest to parse an XML document.

    The nodes instance of type NSArray* will contain NSDictionary* objects that you can parse recursively to get the data you want.

    Or, if you know the scheme of your XML document, you can write an XPath query to get you to a nodeContent or nodeAttribute value directly.

    ASIHTTPRequest *request = [ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://stackoverflow.com/"];
    [request start];
    NSError *error = [request error];
    if (!error) {
        NSData *response = [request responseData];
        NSLog(@"Root node: %@", [[self query:@"//" withResponse:response] description]);
    }
    else 
        @throw [NSException exceptionWithName:@"kHTTPRequestFailed" reason:@"Request failed!" userInfo:nil];
    [request release];
    
    ...
    
    - (id) query:(NSString *)xpathQuery withResponse:(NSData *)respData {
        NSArray *nodes = PerformXMLXPathQuery(respData, xpathQuery);
        if (nodes != nil)
            return nodes;
        return nil;
    }
    

提交回复
热议问题