Search code examples
iosxmlgdataxml

GDataXML updating xml data


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 ?


Solution

  • 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.