Search code examples
iphoneiosxmlnsxml

XCODE NSXML changing the element value


I have a very simple xml file by name options.xml

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

Using NSXML I am trying to change "Tom" to "Jim" and save the file. How can I do that. I read many document and there is no straight forward solution. Can some one help me with the code ?

update: I ended up in trying with Gdatasxml

 -(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 saving the data. Help.


Solution

  • Editing XML is a little difficult in iOS. You need to parse the original xml to a model and then form the xml.

    You can make use of 3rd party library such as GDataXML for forming XML from a data source.

    //Edited user info saved in a dictionary
    NSDictionary *dictionary = @{@"Name": @"Jim", @"Option":@"1"};
    
    GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"Dat"];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        GDataXMLElement *element = [GDataXMLElement elementWithName:key stringValue:obj];
        [rootElement addChild:element];
    }];
    //xml document is formed
    GDataXMLDocument *document = [[GDataXMLDocument alloc]
                                  initWithRootElement:rootElement];
    NSData *xmlData = document.XMLData;
    
    NSString *filePath = [self savedXMLPath];
    //XML Data is written back to a filePath
    [xmlData writeToFile:filePath atomically:YES];