Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Guest Post
Posted by Shahar A on Apr 25th, 2008 | Filed under .Net, C# |

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

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


  1. Sam Said on Apr 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 Nov 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 Nov 5, 2008 :

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

  4. Lezka Said on Apr 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 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

Advertise on Dev102 Bitrix Site Manager

Read reviews and compare prices on : Laptops , Software Like Windows, Office Suites & Many More.

Advertise on Dev102
Write Article for Dev102

Write for us!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More