- (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];
}
这是我对问题的解决方案 - 只有我将之前读取和解析的文件写出的部分...
使用PacMan的解决方案时,我遇到了一个问题,即输出的XML文件没有很好地格式化(没有换行符)。
另一点是,我通常更喜欢使用XPath在XML文档中进行导航。
我的代码是类的一部分,因此我对每个节点都有一个属性(NSString* cfaLayout和NSInteger bitsPerPixel):
-(BOOL) savePropertiesFile{
BOOL isSuccess=FALSE;
NSError* error;
NSXMLElement* currentElement;
NSArray* nodes;
/* parse existing url file before saving it to new url */
if([_documentUrl checkResourceIsReachableAndReturnError:&error]==YES){
self.document=[[NSXMLDocument alloc]
initWithContentsOfURL:_documentUrl
options:0
error:&error];
/* check top node */
nodes=[_document nodesForXPath:@"/ImageFormat-Properties"
error:&error];
if([nodes count]==0){
return FALSE;
}
/* cfa layout */
nodes=[_document nodesForXPath:@"/ImageFormat-Properties/ImageFormatDetails/CFALayout[text()]"
error:&error];
if([nodes count]>0){
currentElement=[nodes objectAtIndex:0];
[currentElement setStringValue:[_cfaLayout lowercaseString]];
}
else{
return FALSE;
}
/* bitsPerPixel */
nodes=[_document nodesForXPath:@"/ImageFormat-Properties/ImageFormatDetails/BitsPerPixel[text()]"
error:&error];
if([nodes count]>0){
currentElement=[nodes objectAtIndex:0];
[currentElement setStringValue:[NSString stringWithFormat: @"%ld", (long)_bitsPerPixel]];
}
else{
return FALSE;
}
}
[_document setDocumentContentKind:NSXMLDocumentXMLKind];
[_document setCharacterEncoding:@"UTF-8"];
[_document validateAndReturnError:&error];
if(error){
return FALSE;
}
[self setDocumentUrl:_documentSaveAsUrl];
NSData* xmlData=[_document XMLDataWithOptions:NSXMLNodePrettyPrint];
isSuccess=[xmlData writeToURL:_documentSaveAsUrl atomically:YES];
return isSuccess;
}
或许对某些人有用...