Extracting info. from XML into Cocoa

我的梦境 提交于 2019-12-02 09:29:04

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!