Search code examples
objective-ccocoansxmldocument

NSXMLDocument - Modifying nodes / attributes


Is there a simple way to update nodes in an NSXMLDocument? I come from a c# background and you can do a simple XmlDocument.SelectSingleNode("XPATH") to select a node and XmlNode.InnerText = "abc" to set the value of the node.

I can't seem to find any methods that let me do this in the Apple NSXMLDocument documentation?

Thanks,
Teja


Solution

  • NSXMLDocument is a subclass of NSXMLNode which has a method nodesForXPath:error: which will, it seems, give you an array containing the nodes you're after. Something along these lines:

    NSError err;
    NSArray * nodes = [myXMLDoc nodesForXPath:theXPath error:&err];
    if( !nodes ){ 
        // handle error
    }
    [[nodes objectAtIndex:0] setStringValue:@"abc"];
    

    There may be another method than setStringValue: that you want to call on the resulting node, perhaps.

    (If the thing with the NSError made you say "WTF?", give the Error Handling Guide a quick glance.)