Saturday, November 22, 2008

LINQ to XML and LINQ to Objects Basic Sample

In this post I will show how to use LINQ to XML and LINQ to Objects, very basic example with sample code.

image  image

First I have created a XML file which contains the Customer Details, as given below

<?xml version="1.0" encoding="utf-8" ?>
<
customers>
    <
customer>
        <
customerid>ALFKI</customerid>
        <
city>Berlin</city>
        <
age>20</age>
    </
customer>
    <
customer>
        <
customerid>BONAP</customerid>
        <
city>Marseille</city>
        <
age>21</age>
    </
customer>
    <
customer>
        <
customerid>CONSH</customerid>
        <
city>London</city>
        <
age>30</age>
    </
customer>
    <
customer>
        <
customerid>EASTC</customerid>
        <
city>London</city>
        <
age>34</age>
    </
customer>
    <
customer>
        <
customerid>FRANS</customerid>
        <
city>Torino</city>
        <
age>35</age>
    </
customer>
    <
customer>
        <
customerid>LONEP</customerid>
        <
city>Portland</city>
        <
age>40</age>
    </
customer>
    <
customer>
        <
customerid>NORTS</customerid>
        <
city>London</city>
        <
age>25</age>
    </
customer>
    <
customer>
        <
customerid>THEBI</customerid>
        <
city>Portland</city>
        <
age>36</age>
    </
customer>
</
customers>

 

I have also created a class with the same properties which I have given in the XML document above, and populating the same data,

public class Customer
{
public string CustomerID { get; set; }
public string City { get; set; }
public int Age { get; set; }
public static IEnumerable<Customer> CreateCustomers()
{
   return new List<Customer>
   {
      new Customer { CustomerID = "ALFKI", City = "Berlin", Age=20   },
      new Customer { CustomerID = "BONAP", City = "Marseille" , Age=21},
      new Customer { CustomerID = "CONSH", City = "London", Age=30    },
      new Customer { CustomerID = "EASTC", City = "London", Age=34    },
      new Customer { CustomerID = "FRANS", City = "Torino", Age=35    },
      new Customer { CustomerID = "LONEP", City = "Portland", Age=40  },
      new Customer { CustomerID = "NORTS", City = "London" , Age=25   },
      new Customer { CustomerID = "THEBI", City = "Portland", Age=26  }    
   };
 }
}

Now I have got the Object ready to query using LINQ with the Same data which I have in my XML Document.

Note above how I'm using the new "Automatic Properties and Object Initializers" feature of C# to define the properties (and avoid having to define a field for them and initialize the Objects). And In all the functions below I am reading the XML Document, using XDocument Class within System.Xml.Linq namespace to open and query document.

First I have to populate the DropDownList in the UI, to display all the Cities, I am reading the Cities from the object alternatively you can also read the same from XML document, both will return the same result. This DropDown will allow the users to select the customers located in the selected City.

public static List<Customer> GetCities()
{
     var customers = from customer in Customer.CreateCustomers()
                     orderby customer.City
                     select new Customer { City = customer.City };
     return customers.ToList();
}

I have also added one more DropDown to let the user to select the DataSource (XML or Object), once both the selection is made, users can click on Get Customers to Get the Customer details. Depending on the DataSource and City, the function below will return the List of Customers wither from XML or the Object.

 

public static List<Customer> GetCustomerFromXML(string city)
{
    XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("CustomerXML.xml"));
    var customers = from customer in xmlDoc.Descendants("customer")
                    where customer.Element("city").Value == city
                    select new Customer
                    {
                        CustomerID = customer.Element("customerid").Value,
                        City = customer.Element("city").Value,
                        Age = Convert.ToInt32(customer.Element("age").Value)
                    };
    return customers.ToList();
}

Similarly I am writing the function below to read the object, and returning the List<Customer> which we can bind directly to the GridView.

public static List<Customer> GetCustomersFromObject(string city)
{
     var customers = from customer in Customer.CreateCustomers()
                     where customer.City == city
                     select new Customer
                     {
                         CustomerID = customer.CustomerID,
                         City = customer.City,
                         Age = customer.Age
                     };
     return customers.ToList();
 }

Note: In the functions above the only trick I've made to the LINQ to XML query is to use the "select new Customer" instead of only "select" clause from "select new" (with no type-name).  With this trick I'm returning a sequence of Customer objects that I can pass from class to class, assembly to assembly, and across web-services.

In the code behind of ASPX Page first I have populated the Cities DropDown to List all the cities on Page_Load, then OnClick of the Get Customers  I have written the code to Get the City, and the DataSource from the DropDownList and Call the appropriate method depending on the DataSource.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //get all the cities
        ddlCity.DataSource = Customer.GetCities();
        ddlCity.DataTextField = "city";
        ddlCity.DataValueField = "city";
        ddlCity.DataBind();
    }
}
protected void btnGetCustomers_Click(object sender, EventArgs e)
{
    //binding the Customer from Object
    if (ddlSource.SelectedValue == "Object")
    {
        gvCustomerDetails.Visible = true;
        lblMessage.Text = "Displaying data from Object";
        gvCustomerDetails.DataSource = Customer.GetCustomersFromObject(ddlCity.Text);
        gvCustomerDetails.DataBind();
    }
    //binding the Customer from XML
    else if (ddlSource.SelectedValue == "XML")
    {
        gvCustomerDetails.Visible = true;
        lblMessage.Text = "Displaying data from XML";
        gvCustomerDetails.DataSource = Customer.GetCustomerFromXML(ddlCity.Text);
        gvCustomerDetails.DataBind();
    }
    else
    {
        gvCustomerDetails.Visible = false;
        lblMessage.Text = "Please select the Data Source";
    }
}

Below is my ASPX code which is very much self explanatory, so I have not given much explanation for that, this just for the control name reference.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        LINQ to Object and LINQ to XML Demo</h3>
    <div>
        <table>
            <tr>
                <td>
                    <label for="source" id="lblSource">
                        Data Source :</label>
                </td>
                <td>
                    <asp:DropDownList ID="ddlSource" runat="server">
                        <asp:ListItem Text="Select Source" Value="0" Selected="True"></asp:ListItem>
                        <asp:ListItem Text="XML" Value="XML"></asp:ListItem>
                        <asp:ListItem Text="Object" Value="Object"></asp:ListItem>
                    </asp:DropDownList>
                </td>
                <td></td>
            </tr>
            <tr>
                <td>
                    <label for="empid" id="lblEmp">
                        Select City :</label>
                </td>
                <td>
                    <asp:DropDownList runat="server" ID="ddlCity"></asp:DropDownList>
                </td>
                <td><asp:Button runat="server" ID="btnGetCustomers" Text="Get Customers" 
                        onclick="btnGetCustomers_Click" /></td>
            </tr>
        </table>
        <br />
        <asp:Label runat="server" ID="lblMessage"></asp:Label>
        <br />
        <asp:GridView ID="gvCustomerDetails" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
 

You can download the sample code from here.

You can refer my previous posts, to see the Example of LINQ To SQL.

You can see the well formatted code in my ASP.NET Blog.

 

For more knowledge you can refer the post below.

http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx

http://www.c-sharpcorner.com/UploadFile/scottlysle/L2OinCS05242008233051PM/L2OinCS.aspx

0 comments:

Post a Comment