Friday, April 22, 2011

Add Data inside xml file using GData parser


In this tutorial we will see how to add a node at runtime using GData xml parser, before beginning with the tutorial I would like to clear some things and that’s the resource group which is present in our application bundle has read only rights you cannot write in the bundle file so in this case what you need to do is copy the file in which you want to do operations into the document directory and then start manipulating that file via some file operations, and before beginning with this tutorial I would recommend that you read my GData xml parser post.

Design Phase: For this post I will not be having any design I would be displaying the output into the console.

Step 1: Create an xml file of your choice and drag it in the resource group, our first step would be to copy this file into the document directory, here's a snap of my xml file that i am using



Step 2: Please check my previous blog for GData and perform the initial settings for GData and then get back to this tutorial. Now once the settings are done we need three functions in order to add the data to the xml file present in the document directory
  • The first function is will help us to get the document directory path.
  • The second function will help us to copy the file from the bundle to the document directory and
  • The third function will help us to add the elements to the xml file which is copied from the bundle to the document directory.
Below given are first two function which you have already seen in my earlier demo of plist


-(NSString*)DocumentDirectoryPath
{
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYES);
NSString *documentFolder = [documentPath objectAtIndex:0];
return documentFolder;
}


-(void)copyFileFromBundle_ToDocument_Directory
{
documentxmlFilePath = [[NSString alloc]init];
documentxmlFilePath = [[self DocumentDirectoryPathstringByAppendingPathComponent:@"Employee.xml"];
NSLog(@"The file name is %@",documentxmlFilePath);
NSString *bundlePath = [[NSBundle mainBundle]pathForResource:@"Employee" ofType:@"xml"];
//the below code copies the said file from the bundle into the document directory
[[NSFileManager defaultManagercopyItemAtPath:bundlePath toPath:documentxmlFilePath error:nil];
}


Step 3: In this step we will see the code snippet to add data into the xml file present in the doc directory


-(void)AddData
{
NSData *xmlData = [[NSData alloc]initWithContentsOfFile:documentxmlFilePath];
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:nil];
GDataXMLElement *mainElement = [GDataXMLNode elementWithName:@"Employee"];
//here you are creating some new nodes with values
GDataXMLElement *nameElement = [GDataXMLNode elementWithName:@"name" stringValue:@"Radix"];
GDataXMLElement *domainElement = [GDataXMLNode elementWithName:@"domain" stringValue:@"Dot Net"];
GDataXMLElement *designationElement = [GDataXMLNode elementWithName:@"designation" stringValue:@"Developer"];
//since employee is the parent node of the above node we need to add these values to it
[mainElement addChild:nameElement];
[mainElement addChild:domainElement];
[mainElement addChild:designationElement];
//ultimately employee element is the child element of the root element  
[xmlDocument.rootElement addChild:mainElement];
//you supply in the details of the new xml data that you want to write to the NSData variable
xmlData = xmlDocument.XMLData;
//finally write the data to the file in the doc directory
[xmlData writeToFile:documentxmlFilePath atomically:YES];
}


I have used the comments to explain you the code section 

Step 4: Into  the application didfinishlaunching method make a call to these two function and then see inside the document directory,


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
[self copyFileFromBundle_ToDocument_Directory];
[self AddData];
    [window makeKeyAndVisible];
    
    return YES;
}


if you are having trouble with finding your application folder then in that case just write the following code snippet so that you can find the your application in the folder 


NSLog(@"Doc dir path = %@",NSHomeDirectory());


Step 5: Press build and go and check out your xml file present in the document directory, here's the output of my xml file present in my doc directory




You may download the source code from here.

iHope that this post has helped you out on how to add data to xml file, in case of any query or errors please mail me or post in a comment so that I can solve those your comments are valuable as they help me in improving my writing skills so any comments positive or negative are always welcome until then 

Happy iCoding and have a great Day. 

15 comments:

  1. Hi ravi I have query regarding xmlparsing i want to parse xml file uiviewcontroller using label can you suggest some method

    ReplyDelete
  2. @anonymous: let me get your question their is an xml file and you are interested in displaying its data in a UILabel ?

    Give me the link of the xml file that you want to parse and i would mail you the code for the same.

    ReplyDelete
  3. hi ravi
    ha i have xml file i want parse it locally and display in uiviewcontroller not in table view.
    Is it possible to display it using label.
    Do explain with simple example

    ReplyDelete
  4. hi, i want to know if you already used the gdata lib on the device.
    On the simulator it works very well i must say, but on the device i can not write on the xml file, just read it.
    What should i do?

    ReplyDelete
  5. Xicolete: Are you trying to write the file in the bundle because if you are then it wont do you any good because bundle is read only, you have to create an xml file in the doc directory first and then add the xml data to it that should do the trick.

    Let me know if you have any issues for the same.

    ReplyDelete
  6. Hi ravi,

    This is really great post. Help me a lot, Just need your help, My problem arise when i want to edit node and attributes value of my existing xml file.

    ReplyDelete
  7. @Anonymous: what sort of issue do you get ?

    ReplyDelete
    Replies
    1. I have an svg file with some predefined tags in it. Each tag has some default value assigned. For example, Add Text.
      In the above example, I need to replace "Add Text" with user defined value as well as attributes value like x, y and fill color. Can we access the particular node and update the existing xml?

      Delete
  8. i applied same code ...but it is not working .....

    ReplyDelete
  9. @Prabal: May i know what are you trying to do, the code that i have posted is working but if you are missing one step then in that case it won't be functional ?

    ReplyDelete
  10. Which step we are missing there !!!!!!!


    uncaught exception 'NSInvalidArgumentException', reason: '-[fxmlAppDelegate copyFileFromBundle_ToDocument_Directory]: unrecognized selector sent to instance 0x5a54d00'

    ReplyDelete
  11. @shiv: The above exception means that you have not wrote the CopyFile FromBundleToDocDir method in the .h part of your AppDelegate and hence you have got the exception anyways what i will do is upload the demo code so that you can see it for reference will do that at the end of the day.

    ReplyDelete
  12. @All: I have added the source code link in the post so that you may download it and review the steps at your end.

    Note: The uploaded source code is in ARC format.

    ReplyDelete
  13. New element is not add in my xml file plz help...

    ReplyDelete
  14. Hi Ravi,
    please don't mind for asking like this. i tried to post my question in your blog but tags were not displayed. , firstly thanks for some useful post. i have got the similar problem can you help me with that please. i am new to iPhone development in my situation i have got the xml like .....


    XXXXXXX

    XXXXXXXX


    from the above xml i parsed the two elements and displayed in a tableview that are "ElectroFusionAcquire" and "WeldNumber" for those two fields i created two textfields . when i the user entered data in to those textfields that text needs to be save in the PLACE OF "XXXXXXXX" above xml could you please suggest me the way to achieve this. because there is no good suggestion in google.
    Thanks for your consideration.

    ReplyDelete