GDataXML updating xml data

ぃ、小莉子 提交于 2019-12-13 20:43:38

问题


I am trying to update an xml file. After suggestion I ended up choosing GdataXml. So I am trying to update options.xml file.

Original File

<Dat>
   <Name>Tom</Name>
   <Option>1</Option>
</Dat>

I need to change "Tom" to "Jim" and save in the same file

Here is the code I tried.

 -(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];


}

But this is not updating options.xml file. Can some one help on this ?


回答1:


The missing line of code you are looking for is

NSData *xmlData = doc.XMLData;

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.



来源:https://stackoverflow.com/questions/17235752/gdataxml-updating-xml-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!