How to update node values and add nodes in xml file?
In my iOS application I can read data from xml code to read xml::
-(NSString *)readxmlFile:(NSString *)fileName ElementName:(NSString *)Element Poisson:(NSInteger *)Index {
xmlelement = Element;
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"xml"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *str,*docStr;
if (myData) {
str = [[NSString alloc] initWithData:myData encoding:NSASCIIStringEncoding];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xml",fileName]];
NSError *error = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if(fileExists)
{
NSLog(@"file exist in document");
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
xmlparser=[[NSXMLParser alloc] initWithData: myData1];
[xmlparser setDelegate:self];
[xmlparser parse];
NSLog(@"Data>>%@",xmlData);
}
}
else {
NSLog(@"file does not exist");
xmlparser=[[NSXMLParser alloc] initWithData: myData1];
[xmlparser setDelegate:self];
[xmlparser parse];
NSLog(@"Data>>%@",xmlData);
BOOL success = [str writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(@"Error: %@", [error userInfo]);
}
else {
NSLog(@"File write is successful");
}
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encodin开发者_Python百科g:NSASCIIStringEncoding];
}
}
return [xmlData objectAtIndex:Index];//pasre data from xml based on node name and save in xmlData
}
but unable to write xml (add nodes and update node values), please guide to me how to add nodes and update node values in xml file.
NSXMLParser is just a parser. It doesn't write XML. It's great for dealing with streams of XML but not so great if you get the whole chunk at once.
Google has written a great XML reading/writing class called GDataXmlNode. Here is a blog post about how to use it. http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml
It's much nicer than using NSXMLParser.
精彩评论