Sorry for the rudimentary question – I need some help. I’m able to get the XML doc and save it. Can’t get editing to work. I want to update the “theme” tag using the contents of a textField and set with an action prior to saving. My editing code obviously not working.
Thanks for the help.
-paul.
<temp>
<theme>note</theme>
</temp>
///////
NSMutableArray* temps = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLDocument *xmlDoc;
NSError *err=nil;
NSString *file = [input1 stringValue];
NSURL *furl = [NSURL fileURLWithPath:file];
if (!furl) {
NSLog(@"Unable to create URL %@.", file);
return;
}
xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:furl options: (NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA) error:&err];
if (xmlDoc == nil) {
xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:furl options:NSXMLDocumentTidyXML error:&err];
}
NSXMLElement* root = [xmlDoc rootElement];
NSArray* objectElements = [root nodesForXPath:@"//temp" error:nil];
for(NSXMLElement* xmlElement in objectElements)
[temps addObject:[xmlElement stringValue]];
NSXMLElement *themeElement = [NSXMLNode elementWithName:@"theme"];
[root addChild:themeElement];
NSString * theTheme = [textField stringValue];
[themeElement setStringValue:theTheme];
Here’s how you can change the theme element in a file. Basically when you setStringValue on an element, the root element is updated with the new value and thus the xmlDoc is also updated because it’s linked to the root element. So you can then just write that to file. As an example, here’s the xml document I started with…
And in this code I change the “first theme” value to “changed theme”. Notice also that my “nodesForXPath” code gets the theme elements directly.