Extracting info. from XML into Cocoa

天涯浪子 提交于 2020-01-30 10:58:27

问题


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

<?xml version='1.0'?>
  <Main xmlns='http://www.abc.uk' version='1.0' name='full'>
    <child1 version='2.0'>
    <value1> xyz </value1>
    <userinfo>
       <name> joe </name>
       <pass> joepass </pass>
   </userinfo>
    </child1>
</Root>

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

From my understanding, child1 is the root with attribute 'version'. 'value1' and 'userinfo' are both elements. In Cocoa, how would I display these values ? I can do a [child elementsForName:@"userinfo" and it displays all the values. I need to specifically extract 'joe' and 'joepass'. Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/3739854/extracting-info-from-xml-into-cocoa

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