linq to xml


Here is how to read an xml file using Linq to Xml.  Suppose we have the following xml file:

<?xml version="1.0" encoding="utf-8" ?>
<COMPANY_URLS>
  <COMPANY>
    <NAME>Microsoft</NAME>
    <LINK>http://www.microsoft.com</LINK>
  </COMPANY>
  <COMPANY>
    <NAME>Oracle</NAME>
    <LINK>http://www.oracle.com</LINK>
  </COMPANY>
  <COMPANY>
    <NAME>IBM</NAME>
    <LINK>http://www.ibm.com</LINK>
  </COMPANY>
</COMPANY_URLS>

First, make sure you are all setup to use linq:

1) Add a reference “System.Xml.Linq” to your project:

image

2) Add using statements for the Linq namespaces and for the IO namspace:

using System.Xml.Linq;

using System.Linq;

using System.IO;

3) Add a method that opens the xml file and loads it into a data table, and returns the loaded data table.

public static DataTable GetLinks()
{

   //Get the path to the folder where your xml files are stored from the webconfig
    string path = ConfigurationManager.AppSettings[“FilesPath"];

    //Store the name of the xml file into a string variable


    string fileName = "\\CompaniesLinks.xml";

    //Concatenate the path with the file name

    string xmlFile = path + fileName;

    //Check if the file exists

    if (File.Exists(xmlFile))
    {

        //Load the file into an XDocument object.  The XDocument class is part of the System.Xml.Linq namespace
        XDocument xmlElem = XDocument.Load(xmlFile);

       //This is the Linq to Xml query expression.  It queries the xml file using the Descendants property of the XDocument

       //object to retrieve all the “COMPANY” elements.  Then we retrieve the child elements of each COMPANY

       //element.  Using the projection features of LINQ we assign them to a new anonymous type with the following properites:  “NAME” and “LINK”. 

//The results will be loaded into an anonymous type sequence of data called “CompaniesLinks “.  The sequence of data is like a collection or array. 

//It supports intellisense and you can also bind it to front end controls by assigning it to their DataSource property.

        var CompaniesLinks = from c in xmlElem.Descendants("COMPANY")
                           select new
                           {
                               NAME = c.Element("NAME").Value,
                               LINK = c.Element("LINK").Value
                           };

        //Next we declare a data table “dtLinks” and add two columns (“Name” and “Link”)

        DataTable dtLinks = new DataTable("dtLinks");
        dtLinks.Columns.Add("Name", typeof(String));
        dtLinks.Columns.Add("Link", typeof(String));

        //Next we loop through the collection we obtained from our link statement.  For each iteration we

        //add a row to the data table and assign values to the columns from the objects we created in

       //Linq statement

        foreach (var element in CompaniesLinks )
        {
            DataRow dataRow = dtLinks.NewRow();
            dataRow["Name"] = element.NAME;
            dataRow["Link"] = element.LINK;
            dtLinks.Rows.Add(dataRow);
        }

//Now that our data table is loaded we can return it

        return dtLinks;
    }

return null;

}

No comments:

Post a Comment