GDataXML更新xml数据 [英] GDataXML updating xml data
问题描述
我正在尝试更新xml文件.提出建议后,我最终选择了GdataXml. 因此,我正在尝试更新options.xml文件.
I am trying to update an xml file. After suggestion I ended up choosing GdataXml. So I am trying to update options.xml file.
原始文件
<Dat>
<Name>Tom</Name>
<Option>1</Option>
</Dat>
我需要将"Tom"更改为"Jim"并保存在同一文件中
I need to change "Tom" to "Jim" and save in the same file
这是我尝试的代码.
-(void)saveToXML
{
NSString* path = [[NSBundle mainBundle] pathForResource:@"options" ofType:@"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"Dat"];
NSArray *mySettings = [doc.rootElement elementsForName:@"Dat"];
for (GDataXMLElement *mySet in mySettings)
{
NSString *name;
NSArray *names = [mySet elementsForName:@"Name"];
if (names.count > 0)
{
GDataXMLElement *childElement = (GDataXMLElement *) [names objectAtIndex:0];
name = childElement.stringValue;
NSLog(childElement.stringValue);
[childElement setStringValue:@"Jim"];
}
}
[xmlData writeToFile:path atomically:YES];
}
但这不是更新options.xml文件.有人可以帮忙吗?
But this is not updating options.xml file. Can some one help on this ?
推荐答案
您正在寻找的缺少的代码行是
The missing line of code you are looking for is
NSData *xmlData = doc.XMLData;
来自 Anupdas答案,关于您的最后一个问题.您当前正在将文件读取到内存中,使用该内存初始化一个新对象,更新该新对象,然后将原始文件的内存写入新文件位置.因此,基本上,您正在读取文件,然后将同一文件写回到文件位置.
from Anupdas answer on your last question. You are currently reading a file into memory, initializing a new object using that memory, updating that new object and then writing the original file's memory into the new file location. So essentially you are reading a file and then writing the same file back to the file location.
这篇关于GDataXML更新xml数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!