Extracting info. from XML into Cocoa

前端 未结 1 1146
深忆病人
深忆病人 2021-01-26 10:41

I am trying to parse an XML to extract values of certain variables. Here\'s an example:


  
相关标签:
1条回答
  • 2021-01-26 11:21

    How do I extract the 'xyz' value to display ? How do I extract 'joe' and 'joepass' to display ?

    With something like this. This assumes you have your XML in an NSString:

    NSXMLDocument* xmlDoc;
    NSError* error = nil;
    NSUInteger options = NSXMLNodePreserveWhitespace|NSXMLDocumentTidyXML;
    xmlDoc = [[NSXMLDocument alloc] initWithXMLString:xmlString
                                              options:options
                                                error:&error];
    if (!error)
    {
        NSArray* value1Nodes = [xmlDoc nodesForXPath:@".//Main/value1" error:&error];
        if (!error)
        {
            NSXMLNode* value1node = [value1Nodes objectAtIndex:0];
            NSString* value1 = [value1node stringValue];
            // .. do something with value1
        }
    
        NSArray* userInfoNodes = [xmlDoc nodesForXPath:@".//Main/userinfo" error:&error];
        if (!error)
        {
            for (NSXMLNode* userInfoNode in userInfoNodes)
            {
                NSXMLNode* nameNode = [[userInfoNode nodesForXPath:@"./name" error:&error] objectAtIndex:0];
                NSXMLNode* passNode = [[userInfoNode nodesForXPath:@"./pass" error:&error] objectAtIndex:0];
                NSString* name = [nameNode stringValue];
                NSString* pass = [passNode stringValue];
                // .. do something with name and pass
        }
    }
    

    See more details in Apple's Tree-Based XML Programming Guide.

    From my understanding, child1 is the root with attribute 'version'. 'value1' and 'userinfo' are both elements.

    Main is the root node in this XML document, not child1.

    0 讨论(0)
提交回复
热议问题