Creating a data layer using LINQ to XML

by Hozefa 11. August 2012 01:39

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. We will take a look on how to perform basic Create, Read, Update and Delete operations on the XML file using LINQ to XML.

Sample structure of ContactsDB.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Contact Id="1">
    <FirstName>Hozefa</FirstName>
    <LastName>Mangalorewala</LastName>
    <Phone>9860515805</Phone>
    <Email>hozefam@gmail.com</Email>
  </Contact>
  <Contact Id="2">
    <FirstName>James</FirstName>
    <LastName>Bond</LastName>
    <Phone>007</Phone>
    <Email>hero@badguys.com</Email>
  </Contact>
</Contacts>

Using the above structure, will make use of XDocument class to load the XML. XDocment is defined in System.Xml.Linq which represents a XML document.

string sFileName = HttpContext.Current.Server.MapPath("~/Data/ContactsDB.xml");
XDocument xmlDoc = XDocument.Load(sFileName);

XDocument on QuickWatch lists out the xml document structure.

Lets look at Create operation on XML using LINQ:

XElement newContact = new XElement("Contact",
    new XElement("FirstName", oContact.FirstName),
    new XElement("LastName", oContact.LastName),
    new XElement("Phone", oContact.Phone),
    new XElement("Email", oContact.Email));

newContact.SetAttributeValue("Id", GetNextAvailableID());

xmlDoc.Element("Contacts").Add(newContact);
xmlDoc.Save(sFileName);

 This creates a XElement Contact with inner XElements of FirstName, LastName, Phone, Email and Id. Note: Since Id may have requirement to be unique, the snippet above populates the Id by performing a sort logic within GetNextAvailableID().

Now, Read operation on XML using LINQ:

XDocument xmlDoc = XDocument.Load(sFileName);

return (from c in xmlDoc.Descendants("Contact")
        orderby c.Attribute("FirstName")
        where c.Attribute("Id").Value.Equals(Id.ToString())
        select new Contact()
        {
            Id = Convert.ToInt32(c.Attribute("Id").Value),
            FirstName = c.Element("FirstName").Value,
            LastName = c.Element("LastName").Value,
            Phone = c.Element("Phone").Value,
            Email = c.Element("Email").Value
        }).FirstOrDefault();

To return a list of Contacts, just replace the FirstOrDefault() with ToList() and exclude the where condition to refrain a matching Contact lookup.

Now, Update operation on XML using LINQ:

XElement contactElement = xmlDoc.Descendants("Contact")
    .Where(c => c.Attribute("Id").Value.Equals(oContact.Id.ToString()))
    .FirstOrDefault();

if (contactElement != null)
{
    contactElement.SetElementValue("FirstName", oContact.FirstName);
    contactElement.SetElementValue("LastName", oContact.LastName);
    contactElement.SetElementValue("Phone", oContact.Phone);
    contactElement.SetElementValue("Email", oContact.Email);
    xmlDoc.Save(sFileName);
}

and finally the Delete operation using LINQ to XML:

XDocument xmlDoc = XDocument.Load(sFileName);

XElement customerElement = xmlDoc.Descendants("Contact")
    .Where(c => c.Attribute("Id").Value.Equals(oContact.Id.ToString()))
    .FirstOrDefault();

if (customerElement != null) 
{ 
    customerElement.Remove(); 
    xmlDoc.Save(sFileName); 
}

 Using the above methods we can create an abstract application that will perform CRUD operations on XML.

Tags: , ,

.NET | LINQ

Comments (1) -

Thomasina Tansey
Thomasina Tansey United States
8/24/2012 2:09:41 AM #

I just want to say I'm beginner to blogs and absolutely loved you're blog site. More than likely I'm going to bookmark your site . You surely come with tremendous writings. With thanks for sharing your web page.

Reply

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List