Sunday, April 12, 2009

LINQ (Language Integrated Query) C#: Appending to existing XML files using DotNET Framework 3.5

LINQ has been one of the greatest innovations in the recent trends of programming. And this comes from the Microsoft.

I really like the easiness of interacting with XML files. Now writing, reading, appending an XML (using the LINQ TO XML features of Microsoft Framework 3.5) has become very easy and, is no more complicated as it was before (atleast for me, LOL).

In this program i explain how to APPEND an XML file using LINQ TO XML Features of C# in Framework 3.5

Let us consider the following XML file.






the following program explains how to append to existing XML files.

This program would be quite useful in writing log files/ appending to xml files.



consider the following program.

using System;
using System.IO;
using System.Xml.Linq;
using System.Linq;

class LinqAppendXML
{
static void Main()
{


XDocument xml = XDocument.Load(@"C:\xml\test.xml");

Console.Write("successfully loaded the xml file");

//getting to the root element.

XElement t = xml.Root;

//adding new element to the root element

t.Add(new XElement("login",new XAttribute("time",
DateTime.Now.ToString()),
new XAttribute("id", "some name")));

xml.Save(@"C:\xml\test.xml");                            

}
}
The program produces the following output:






This way an xml files can be appended. This is one of the most easiest way to append to a existing XML file.

4 comments:

  1. what is thing do??? programming?? explain please...

    ReplyDelete
  2. do you have any idea about C# ??

    this is a way to append existing XML file,

    like log files, adding new data to existing data(append) using System.Xml.Linq namespace.

    ReplyDelete
  3. hi rahul,

    i am building a windows application in which i have to fetch a desired data from a xml document. eg the name of student with id 01.
    can you plz give me the c# code for the following???

    ReplyDelete
  4. @anubhav:
    The following is a good resource, tweak the xml and c# code accordingly.

    http://msdn.microsoft.com/en-us/library/bb387013.aspx

    http://stackoverflow.com/questions/670563/linq-to-read-xml-c

    cheers,
    Rahul Kavi

    ReplyDelete