Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and update value in xml file in iOS?

Tags:

ios

In iOS, I am reading a xml file. Here I want to write the xml file and I want to change the values of the XML file and I want to save the file.

My code is like below... Please guide me how to save and update value in xml file.

-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName nodename:(NSString *)nodename{


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // the path to write file
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xml",fileName]];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
    if(fileExists) {
        NSError *error = nil;
        NSString *docStr;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        // the path to write file
        NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xml",fileName]];

        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
        if(fileExists)
        {
            NSLog(@"file exist in document");
            NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
            if (myData1) {  
                docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];

            } 
        }
        NSMutableString *str = [[NSMutableString alloc] init];
        NSString *aaa=[NSString stringWithFormat:@" <%@>%@</%@>",nodename,data,nodename];
        [str appendString:docStr];

        [str insertString:aaa atIndex:70];
        BOOL success = [str writeToFile:appFile  atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (!success) {
            NSLog(@"Error: %@", [error userInfo]);
        }
        else {
            NSLog(@"File write is successful");
        }
    }
}
like image 501
Navya sri Avatar asked Jul 08 '11 06:07

Navya sri


People also ask

How do I update an XML file?

To update data in an XML column, use the SQL UPDATE statement. Include a WHERE clause when you want to update specific rows. The entire column value will be replaced. The input to the XML column must be a well-formed XML document.

How create XML file in IOS?

File>New>File... -> Empty and then name it Whatever. xml before clicking 'Create' or just drag an xml file to the project navigator and make sure 'Copy if needed' is checked.


2 Answers

In short,

  1. use an XML parser to read the XML
  2. represent the XML in some kind of object structure (data binding)
  3. modify the object structure; this is where you insert your new elements etc
  4. use an XML serializer to write the XML (making your own XML is not recommended) from the object structure

In steps 1 and 4 you either go via NSData or read directly from file, depending on the XML parser and writer API.

You can use NSXMLParser to parse the XML, and libxml(2) to writer, alternatively other readers and writers (this one by me).

like image 152
ThomasRS Avatar answered Oct 17 '22 02:10

ThomasRS


Use libxml2 dylib available in the xcode links library sections and use xmlwriter class for creating your xml files. sample code

xmlTextWriterPtr _writer;
xmlBufferPtr _buf;
xmlChar *xmlString;
const char *_UTF8Encoding = "UTF-8";

_buf = xmlBufferCreate();
_writer = xmlNewTextWriterMemory(_buf, 0);

// <?xml version="1.0" encoding="UTF-8"?>
xmlTextWriterStartDocument(_writer, "1.0", _UTF8Encoding, NULL);

xmlTextWriterStartElement(_writer, BAD_CAST "root");

    // <request type="handle" action="update">
xmlTextWriterStartElement(_writer, BAD_CAST "child");

xmlString = [self xmlCharPtrForInput:[[NSString stringWithFormat:@"%@",objPatient.strFname] cStringUsingEncoding:NSUTF8StringEncoding] withEncoding:_UTF8Encoding];
xmlTextWriterWriteAttribute(_writer, BAD_CAST "fname", BAD_CAST xmlString);

xmlTextWriterEndElement(_writer);//Close child
xmlTextWriterEndElement(_writer); //close root here

The method xmlcharptrforinput is,

- (xmlChar *) xmlCharPtrForInput:(const char *)_input withEncoding:(const char *)_encoding 
{
    xmlChar *_output;
    int _ret;
    int _size;
    int _outputSize;
    int _temp;
    xmlCharEncodingHandlerPtr _handler;

    if (_input == 0)
        return 0;

    _handler = xmlFindCharEncodingHandler(_encoding);

    if (!_handler) {
        //NSLog(@"convertInput: no encoding handler found for '%s'\n", (_encoding ? _encoding : ""));
        return 0;
    }

    _size = (int) strlen(_input) + 1;
    _outputSize = _size * 2 - 1;
    _output = (unsigned char *) xmlMalloc((size_t) _outputSize);

    if (_output != 0) {
        _temp = _size - 1;
        _ret = _handler->input(_output, &_outputSize, (const xmlChar *) _input, &_temp);
        if ((_ret < 0) || (_temp - _size + 1)) {
            if (_ret < 0) {
                //NSLog(@"convertInput: conversion wasn't successful.\n");
            } else {
                //NSLog(@"convertInput: conversion wasn't successful. Converted: %i octets.\n", _temp);
            }   
            xmlFree(_output);
            _output = 0;
        } else {
            _output = (unsigned char *) xmlRealloc(_output, _outputSize + 1);
            _output[_outputSize] = 0;  //null terminating out
        }
    } else {
        //NSLog(@"convertInput: no memory\n");
    }

    return _output;
}
like image 43
Futur Avatar answered Oct 17 '22 04:10

Futur