I was in error, when I claimed that writing such elements couldn't be done.
Apple have two XML parsers, one for NSDictionary/NSArray/NSString/NSNumber/etc. objects and one called NSXMLDocument.
I've removed the previous code, which was Mac OS X 10.3 compatible; the code mentioned below will allow you to have xml files containing whatever tags and attributes you like.
In my example, the code will create an XML file that looks like the following:
<root><counter>1</counter></root>
Note: You can even remove the 'counter' and rename 'root' to 'counter', if you want to reduce it further.
The new code is compatible with Mac OS X 10.4 and forward; it's tested and works out-of-the-box:
- (void)incrementCounter
{
NSXMLDocument *xmlDoc;
NSError *error;
NSURL *url;
NSXMLElement *root;
id item;
NSData *data;
NSArray *children;
int counter;
NSString *pathname;
pathname = [@"~/myFile" stringByExpandingTildeInPath];
url = [NSURL fileURLWithPath:pathname];
xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:url options:NSXMLDocumentTidyXML error:&error];
if(xmlDoc)
{
root = [xmlDoc rootElement];
}
else
{
root = [NSXMLNode elementWithName:@"root"];
xmlDoc = [[NSXMLDocument alloc] initWithRootElement:root];
}
// fetch value:
children = [root nodesForXPath:@"counter" error:&error];
item = [children count] ? [children objectAtIndex:0] : NULL;
// modify value:
counter = item ? [[item stringValue] intValue] : 0;
counter++;
if(NULL == item)
{
item = [NSXMLNode elementWithName:@"counter" stringValue:@"0"];
[root insertChild:item atIndex:0];
}
[item setStringValue:[[NSNumber numberWithInt:counter] stringValue]];
// write:
data = [xmlDoc XMLData];
[data writeToURL:url atomically:YES];
}