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" ?>
  <user id="149">
  <user id="13">
  <user id="45">

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")));


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>();


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>();


That’s it for now. Happy coding.


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: