tags:

views:

29

answers:

1

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  A: 

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.

Shaggy Frog
Thanks. That worked brilliantly.