I am trying to parse an XML to extract values of certain variables. Here\'s an example:
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
.