Confessions of a .NET Developer!

Basic Linq to XML operations

This post shall deal with Inserting, Deleting and Modifying XML data using Linq to XML.

Here is how the XML will look like:

<?xml version="1.0" encoding="utf-8" ?>
<access>
  <user id="149">
    <name>Tarun</name>
    <age>22</age>
    <company>ABC</company>
  </user>
  <user id="13">
    <name>Gagan</name>
    <age>23</age>
    <company>Birla</company>
  </user>
  <user id="45">
    <name>Sachin</name>
    <age>24</age>
    <company>Steria</company>
  </user>
</access>

Add this XML to your project or create one using the XML Editor and set its Build Action to “Content” instead of Resource and also set Copy to Output Directory to “Copy if Newer”. With its build action set to content, I can modify the XML.

The code to Load the XML using the XDocument class under the namespace System.Xml.Linq

XDocument xDoc = XDocument.Load("XMLAccess.xml");
XElement rootElem = xDoc.Root;

And here is the way to Insert a new Record(User) into the XML :

            rootElem.Add(new XElement("user",
                new XAttribute("id", 90),
                new XElement("name", "Pulkit"),
                new XElement("age", 19),
                new XElement("company", "Infosys")));

            xDoc.Save("XMLAccess.xml");

Its quite simple using Linq, and a lot messier in case of the standard XmlDocument class.

The code to delete a User:

            XElement delElem = (from XElement elem in xDoc.Descendants("user")
                                where int.Parse(elem.Attribute("id").Value) == 90
                                select elem).Single<XElement>();

            delElem.Remove();
            xDoc.Save("XMLAccess.xml");

So the above Linq expression will return a single XElement of type user of id=90 and gets removed using a simple Remove() function.

And the code to update the XML :

            XElement updElem = (from XElement elem in xDoc.Descendants("age")
                                where int.Parse(elem.Parent.Attribute("id").Value)==45
                                select elem).Single<XElement>();

            updElem.SetValue(48);
            xDoc.Save("XMLAccess.xml");

That’s it for now. Happy coding.

Advertisements

May 4, 2011 - Posted by | LINQ, XML

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: