Click here to Skip to main content
11,929,950 members (49,427 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


9 bookmarked

Working with LINQ to XML

, 13 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Creating an ASP.NET website and working with LINQYou can use LINQ to XML for following purposes-1. For creating xml file.2. For loading an xml file.3. For querying xml data.4. Manipulating xml data.5. Transforming the xml into another shape.In this example we will load an already created xml file. W

Creating an ASP.NET website and working with LINQ

You can use LINQ to XML for following purposes-
  1. For creating xml file.
  2. For loading an xml file.
  3. For querying xml data.
  4. Manipulating xml data.
  5. Transforming the xml into another shape.

In this example we will load an already created xml file. We will use Contacts.xml file. The content of this file is as shown below-

<id> 1 </id>

Follow the below steps to query through the xml file

  1. Open Visual Studio and create an ASP.NET website called Linq2Xml by using C#.
  2. Add the above created Contacts.xml file to the App_Code directory of your solution.
  3. Add a new class file called Contact.cs to the solution. This class represents an contact object and will be used when the xml is turned to a collection of strongly typed objects. The following code shows an example
    namespace Linq2Xml
        public class Contact
            public int id { get; set; }
            public string name { get; set; }
            public string department { get; set; }
  4. Add a new class file called ContactServices.cs. This class will expose methods that use LINQ to work with the xml file. Add following code to this file.
    1. Add a class level variable to read the class file. Also, add the reference for namespace System.Xml.Linq.
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web; 
      using System.Xml.Linq;
      namespace Linq2Xml
          public class ContactServices 
              XElement _conXml = XElement.Load("c:\\....\\visual studio 2010\\Projects\\Linq2Xml\\Linq2Xml\\App_Data\\Contacts.xml");
      . . . 
      // define methods here
    2. Add a method called GetDepartments to return the distinct departments from the xml file.
      public List<string> GetDepartments()
                  var deptQuery =
                      from con in _conXml.Descendants("contact")
                      group con by con.Element("department").Value
                          into conGroup
                          select conGroup.First().Element("department").Value;
                  return deptQuery.ToList();
    3. Add another method called GetContactsByDept that takes department as a parameter. It will then query the xml file and returns department with a matching name. The query will transform data into a list of Contact object.
      public List<Contact> GetContactsByDept(string department)
                  IEnumerable<Contact> conQuery =
                      from con in _conXml.Descendants("contact")
                      where con.Element("department").Value == department
                      select new Contact
                          id = Convert.ToInt32(con.Element("id").Value),
                          department = con.Element("department").Value,
                          name = con.Element("name").Value,
                  return conQuery.ToList();
  5. Open the default.aspx page. Add a label, Dropdown list, Button, GridView and ObjectDataSource controls to the page.
  6. Configure the ObjectDataSource to point to ContactServices.GetDepartments method.
  7. Configure the dropdown list to use the ObjectDataSource. The markup inside the MainContent placeholder should look similar to the following
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <asp:Label ID="Label1" runat="server" Text="Select a department:"></asp:Label>
        <br />
        <br />
        <asp:DropDownList ID="DropDownListDepts" runat="server" DataSourceID="ObjectDataSourceDept">
        <asp:Button ID="Button1" runat="server" Text="Update " onclick="Button1_Click" />
        <br />
        <br />
        <asp:GridView ID="GridViewContacts" runat="server">
        <br />
        <asp:ObjectDataSource ID="ObjectDataSourceDept" runat="server" SelectMethod="GetDepartments"
  8. Add a click event to the button control. Inside the code for the click event, call the ContactServices. GetContactsByDept method and pass the selected method from the dropdown list. Update the data in the gridView control with the results. The following code shows an example
    protected void Button1_Click(object sender, EventArgs e)
                ContactServices conSrv = new ContactServices();
                GridViewContacts.DataSource =
  9. Run your application. Select a department and click on Update button.  Your result should look similar to the below figure.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Komal Mangal
Software Developer
India India
For more technical articles please visit my blog at-

You may also be interested in...

Comments and Discussions

SuggestionLINQ to SQL ? Pin
DotNetMan13-Jan-14 7:31
memberDotNetMan13-Jan-14 7:31 
GeneralRe: LINQ to SQL ? Pin
Komal Mangal13-Jan-14 8:19
memberKomal Mangal13-Jan-14 8:19 
GeneralRe: LINQ to SQL ? Pin
Arvind Singh Baghel28-May-14 1:55
memberArvind Singh Baghel28-May-14 1:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 13 Jan 2014
Article Copyright 2014 by Komal Mangal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid