XML Parsing in Cocoa Touch/iPhone

后端 未结 3 1932
南方客
南方客 2020-12-09 13:49

Okay i have seen TouchXML, parseXML, NSXMLDocument, NSXMLParser but i am really confused with what to to do.

I have an iphone app which connects to a servers, reques

3条回答
  •  情话喂你
    2020-12-09 14:24

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

    To parse XML, use PerformXMLXPathQuery instead of the PerformHTTPXPathQuery I use in my example.

    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 = PerformHTMLXPathQuery(respData, xpathQuery);
        if (nodes != nil)
            return nodes;
        return nil;
    }
    

提交回复
热议问题