Linq to xml provides an easy query interface for XML files. In the following example I will demonstrate how to use linq to xml to read and write data from/to xml file, using the file for persistency maintaining a list of objects. linq to xml can be used for storing application settings, storing persistent objects or any other data needs to be saved. Follow the 3 steps to get the picture and see how easy it is:

  1. Define the Data Entity
  2. Create XML Data File
  3. Load/Save the Data…

Lets check out the these three steps for using linq to xml

1. Define the Data Entity

In this example we’ll be dealing with patients, so lets define a Patient class with some attributes:

class Patient
{
    public string EMail { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

 

2. Create XML Data File

<?xml version="1.0" encoding="utf-8" ?>
<Patients>
  <Patient EMail="LeBron@James.com">
    <FirstName>LeBron</FirstName>
    <LastName>James</LastName>
  </Patient>
  <Patient EMail="Kobe@Bryant.com">
    <FirstName>Kobe</FirstName>
    <LastName>Bryant</LastName>
  </Patient>
  <Patient EMail="Allen@Iverson.com">
    <FirstName>Allen</FirstName>
    <LastName>Iverson</LastName>
  </Patient>
</Patients>

 

3. Load/Save the data

I Inherited the List<Patient> and add Load/Save methods to it:

class PatietList : List<Patient>
{
    public void Load(string xmlFile)
    {
        XDocument doc = XDocument.Load(xmlFile);     

        var query = from xElem in doc.Descendants("Patient")
                    select new Patient
                    {
                        EMail = xElem.Attribute("EMail").Value,
                        FirstName = xElem.Element("FirstName").Value,
                        LastName = xElem.Element("LastName").Value,
                    };     

        this.Clear();
        AddRange(query);
    }     

    public void Save(string xmlFile)
    {
        XElement xml = new XElement("Patients",
                        from p in this
                        select new XElement("Patient",
                            new XAttribute("EMail", p.EMail),
                            new XElement("FirstName", p.FirstName),
                            new XElement("LastName", p.LastName)));     

        xml.Save(xmlFile);     

    }     

}

See how easy this is? get familiar with the XDocument, XElement and XAttribute classes.

Another thing you could do is to move load/save knowledge into the Data object:

class Patient
{
    ...
    public Patient(XElement xElement)
    {
        EMail = xElement.Attribute("EMail").Value;
        FirstName = xElement.Element("FirstName").Value;
        LastName = xElement.Element("LastName").Value;
    }     

    public XElement XElement
    {
        get
        {
            return new XElement("Patient",
                    new XAttribute("EMail", EMail),
                    new XElement("FirstName", FirstName),
                    new XElement("LastName", LastName));
        }
    }
    ...
}

and than the load/save query looks like this:

public void Load(string xmlFile)
{
    ...
    var query = from xElem in doc.Descendants("Patient")
                select new Patient(xElem);
    ...     

public void Save(string xmlFile)
{
    ...
    XElement xml = new XElement("Patients",
                    from p in this
                    select p.XElement);

Tags :

16 Responses to “LINQ to XML in 3 easy steps”


  1. Sam

    Said on April 29, 2008 :

    Linq is so neat. I bought a book on it though and the book isn’t really as good as many online resources like this one. Thanks for adding your knowledge to the community’s database.

  2. Larry

    Said on November 5, 2008 :

    I ran a variation of this with my own xml, where xml file looked like:

    XML File:

    Bob

    Bob1

    False

    2146836480

    My Code snippet:

    —- Usings:
    using System.Collections.Specialized;
    using System.Collections.Generic;
    using System.IO;
    using System.Diagnostics;
    using System.Xml.Linq;

    class Key
    {
    public string Name { get; set; }
    public string Value { get; set; }

    }

    class KeyList: List
    {
    public void Load(string xmlFile)
    {
    XDocument doc = XDocument.Load(xmlFile);

    var query = from xElem in doc.Descendants(“Key”)
    select new Key
    {
    Name = xElem.Attribute(“Name”).Value,
    Value = xElem.Element(“Value”).Value,
    };
    this.Clear();
    AddRange(query);
    }
    }

    My method getting data:
    private static string GetMachineConfig(string Dimension)
    {
    KeyList MyKeys = new KeyList();
    MyKeys.Load(“D:\\Log\\MachineConfig.xml”);

    foreach (Key ky in MyKeys)
    {
    if (ky.Name == Dimension)
    {
    return ky.Value;
    }
    }
    return “Not Found”;

    }

    My compiler error:
    Could not find an implementation of the query pattern for source type ‘System.Collections.Generic.IEnumerable’. ‘Select’ not found. Are you missing a reference to ‘System.Core.dll’ or a using directive for ‘System.Linq’? c:\BuildJobBat\Program.cs 23 39 BuildJobBat

  3. Larry

    Said on November 5, 2008 :

    Note: web app stripped some code out of the example, email me for actual code snippet.

  4. Lezka

    Said on April 28, 2009 :

    Hi,

    I have an xml with elements like this

    how can I store the list of files in the new Module created by the sql?

  5. Marcio

    Said on May 23, 2009 :

    Very good article.Is anybody there could show me how to get the results from a Linq query and populate a DataSet?
    That way the data can be placed in a DataGridView. I am trying to do this but no results yet.

  6. Rob

    Said on March 15, 2010 :

    Ok I give in, I tried to get linq -> DataTable going, but it was horrible. So I tried dealing directly with linq -> xml, that was even horribler (I claim the rights to that word).

    Which ever you do you end up with ugly code and neither makes using your application’s stored data easier to use than the good old fashioned ‘Do it yourself straight from classes’ method. Why on earth didn’t MS make a nice Linq->DataTable/Set marriage.

    As for the Linq->XML side, instead of making the marriage as easy to use as Linq, they have made it as horrible to use as XML. Maybe their developers miss read the design spec.

    You are right, best way is to just load the data into a regular class and forget about the XML side from then on (or until you need to update the file. But then you start to wonder why you are keeping the data in an XML file, I mean, if the only program using your data is your application and it’s relatives, then XML is just too much of a pain in the big bit at the top of your legs around the back.

  7. Australian Amusements Directory

    Said on May 4, 2010 :

    Good tutorial.

  8. Mike Pliam

    Said on June 26, 2010 :

    class PatietList : List

    will not compile using VS 2008.

    The non-generic type ‘List’ cannot be used with type arguments.

    Also, I assume you meant ‘PatientList’ (sp). Taking a bit more time to go over your posts would probably save many of us alot of time.

  9. Warren

    Said on August 4, 2011 :

    Has anyone converted this to vb.net.. I can do it in C#, but the code base I am working with is vb and I am not sure how to do teh part that “cast” the linq results in a class…
    var query = from xElem in doc.Descendants(“Patient”)
    select new Patient
    {
    EMail = xElem.Attribute(“EMail”).Value,
    FirstName = xElem.Element(“FirstName”).Value,
    LastName = xElem.Element(“LastName”).Value,
    };

  10. fully

    Said on September 8, 2011 :

    Hey, Thank for your article but i cant write keyword “this” without a error

    XElement xml = new XElement(“Customers”,
    from p in this // <== error at keyword this
    select new XElement(“Customer”,
    new XElement(“name”,”John Cherry”),
    new XElement(“phone”,”2134-234-324″),
    new XElement(“address”,”Hai Phong”)));

    Specify this error is :
    Could not find an implementation of the query pattern for source type ‘DAL_GALLERY’. ‘Select’ not found.

    Someone help me, please !

6 Trackback(s)

  1. Apr 25, 2008: LINQ to XML in 3 easy steps « Rams On It - .NET
  2. Apr 28, 2008: Weekly Link Post 39 « Rhonda Tipton’s WebLog
  3. Apr 28, 2008: Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, jQuery, CSS, C#… | Code-Inside Blog
  4. Apr 28, 2008: Weekly Links: ASP.NET MVC, Silverlight 2, jQuery, CSS, C#… | Code-Inside Blog International
  5. May 8, 2008: Clonopin     » LINQ to XML in 3 easy steps
  6. Apr 17, 2009: Dev102.com March 2009 Roundup | Dev102.com

Post a Comment