Using LINQ to XML


Here I would like to explain how to use LINQ to Query XML and XML Objects. As we know, XML is extensively used because of its popularity. XML provides data in a more accurate, flexible, and adaptable way.

Using LINQ to XML



Here I would like to explain how to use LINQ to Query XML and XML Objects. As we know, XML is extensively used because of its popularity. XML provides data in a more accurate, flexible, and adaptable way.
LINQ is more a query tool to Query different type of Data. Either it can used to query different types of Objects, SQL Data, and XML Data etc.
I have already given sample how to query Objects; here I am going to use XML data instead.
Creating XML Tree using LINQ


private void btnCreate_Click(object sender, EventArgs e)
{
try
{
//Creating XML Tree using the LINQ to XML Object and Save that in XML file

XDocument doc = new XDocument();
XElement contactsList =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Kapil"),
new XElement("Phone", "206-555-0144",
new XAttribute("Type", "Home")),
new XElement("Phone", "425-555-0145",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street1", "300 Colonial Centre Pkwy"),
new XElement("City", "Roswell"),
new XElement("State", "GA"),
new XElement("Postal", "30076")
)
),
new XElement("Contact",
new XElement("Name", "Yashu"),
new XElement("Phone", "206-555-0144",
new XAttribute("Type", "Home")),
new XElement("Phone", "425-555-0145",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street1", "300 Colonial Centre Pkwy"),
new XElement("City", "Roswell"),
new XElement("State", "GA"),
new XElement("Postal", "30076")
)
)
);

// Save the contact in XML file
contactsList.Save("C:\\Save.xml");
}
catch (XmlException ex)
{
MessageBox.Show(ex.Message);
}
}


In above piece of code, I am using XML Object to create XML tree using LINQ. You can use the XML DOM also to create the tree, but using the LINQ XML it is more efficient and faster. It is faster because LINQ to XML provides an in-memory XML programming interface.
Functional construction uses the XElement and XAttribute constructors to build an XML tree. Here we constructed the XML tree using the LINQ to XML functional construction.
Show XML Data Using LINQ

Here I am Using LINQ to show (display) the XML Data from the XML file. Below is the Form I will be using throughout this article.

LINQ to XML Form

Designer Code

I am just showing the name of the fields from the designer, You can create the form and use the following name.



this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.btnShow = new System.Windows.Forms.Button();
this.btnCreate = new System.Windows.Forms.Button();
this.lblName = new System.Windows.Forms.Label();
this.lblPhone = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtName = new System.Windows.Forms.TextBox();
this.txtPhoneWork = new System.Windows.Forms.TextBox();
this.txtPhoneHome = new System.Windows.Forms.TextBox();
this.txtStreet = new System.Windows.Forms.TextBox();
this.txtCity = new System.Windows.Forms.TextBox();
this.txtState = new System.Windows.Forms.TextBox();
this.txtPin = new System.Windows.Forms.TextBox();
this.btnShow1 = new System.Windows.Forms.Button();
this.SuspendLayout();

private void btnShow_Click(object sender, EventArgs e)
{
// Load the XML file using XElement, you can load the xml with different object also
// XMLReader can also be used to load or read the xml
// In following we are searching the xml which has the element name=Kapil and get the elment for that Node
// Now we get the filltered data which is another set of xml (element), now you can use the IEnuramble to enumarte and display the each
// Item in text field or where you need that.

XElement contacts = XElement.Load("C:\\Save.xml");

XElement filterName = new XElement("FilteringByName",
from contact in contacts.Elements("Contact")
where (string)contact.Element("Name").Value == "Kapil"
select new XElement("Contact", contact.Elements()
)
);
richTextBox1.Text = filterName.ToString();
}


In the above piece of code, we are loading the XML file using XElement LINQ Object. You can show whole XML but I am filtering the XML Data based on the Name element. To filter the data I am using LINQ to Query the XML data based on name.

As you see in code, it is like your SQL Query where you are looking into the XML with where clause to filter out the data. Select has been used to return the Element Data for that name specified in where clause.
The result will be shown in Text filed as



Kapil
206-555-0144
425-555-0145

300 Colonial Centre Pkwy
Roswell
GA
30076




LINQ to XML Form

Show Contact Information

As show in the above screen I am showing the contact information in each field from XML Data. In traditional XML DOM Object that can be accomplished by using the XPath or selecting each node from XML Element.
But here we are going to use the LINQ to query the each node of the XML element and display in the appropriate filed.



private void ShowContact(XElement element)
{
XElement contactname = new XElement("Name", from name in element.Element("Contact").Elements("Name")
select new XElement("Name",name.Value));

var contactphonew = (from phone in element.Element("Contact").Elements("Phone")
where (string)phone.Attribute("Type") == "Work"
select phone);

XElement contactphoneh = new XElement("PhoneHome",from phone in element.Element("Contact").Elements("Phone")
where (string)phone.Attribute("Type") == "Home"
select new XElement("Phone",phone.Value));

IEnumerable contactaddress = from name in element.Element("Contact").Elements("Address")
select name;

txtName.Text = contactname.Value;
txtPhoneWork.Text = ((XElement)contactphonew.First()).Value;
txtPhoneHome.Text = contactphoneh.Value;

foreach(XElement address in contactaddress)
{
txtStreet.Text = address.Element("Street1").Value;
txtCity.Text = address.Element("City").Value;
txtState.Text = address.Element("State").Value;
txtPin.Text = address.Element("Postal").Value;
}
}



LINQ is as powerful as shown in above code, the pattern for each query is similar. Here I have used the different approaches to use the LINQ. Drilling down to each element and getting their values.

Using Object Value to Store the Values

Here I am going to show different mechanism to Query the Element and Store in Class Object (Object Values).

To make it simple I have a Class with some property



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToXML
{
public class ContactDataObject
{
public string Name { get; set; }
public string PhoneHome { get; set; }
public string PhoneWork { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
}
}


LINQ Query

Now we can use LINQ to query the XML file and store the relevant data to object. The mechanism is same to query the XML using somewhat similar syntax. The difference here is we are storing the data while we are queering the XML file for that person name.



public ContactDataObject SetContact(XElement element) {

ContactDataObject data = (ContactDataObject)(from contact in element.Descendants("Contact")
select new ContactDataObject()
{
Name = contact.Element("Name").Value,
Street = contact.Element("Address").Element("Street1").Value,
City = contact.Element("Address").Element("City").Value,
State = contact.Element("Address").Element("State").Value,
Postal = contact.Element("Address").Element("Postal").Value,
PhoneHome = (from phone in contact.Elements("Phone")
where (string)phone.Attribute("Type") == "Home"
select new XElement("Phone",phone.Value)).First().Value
}).FirstOrDefault();
return data;
}


In above we are passing the Element and storing the values to property of ContactDataObject class. Below is the code how we are calling the above function and displaying the data to field.


private void btnShow1_Click(object sender, EventArgs e) {

XElement contacts = XElement.Load("C:\\Save.xml");

XElement filterName = new XElement("FilteringByName",
from contact in contacts.Elements("Contact")
where (string)contact.Element("Name").Value == "Kapil"
select new XElement("Contact", contact.Elements()
)
);
richTextBox1.Text = filterName.ToString();
ContactDataObject data = SetContact(filterName);
txtName.Text = data.Name;
txtPhoneHome.Text = data.PhoneHome;
txtStreet.Text = data.Street;
txtCity.Text = data.City;
txtState.Text = data.State;
txtPin.Text = data.Postal;
}



I hope that will guide most of the people how to use the LINQ to query or get the data from XML file. I have taken simple scenario for understanding.


Comments

Author: Subhashini Janakiraman21 Jan 2011 Member Level: Silver   Points : 1

The sample code given is excellent.I have a query.You have saved the LINQ sample to XML File without using XDocument and the XML file is loaded using XElement instead of XDocument?Is it possible?

Author: Kapil18 Feb 2011 Member Level: Gold   Points : 1

Hi Subhashini,

First of all thanks that you like the article and sample code. Sorry for being late reply. Yes, that is possible. If you take the code and run it will work. XElement of LINQ has the capability to load the XML, you can use the Xdocument too if you like.

-Kapil

Author: Umesh Bhosale26 Mar 2014 Member Level: Silver   Points : 0

Hi
As you provide XML file which is well Formatted so you can also use DataSet.ReadXml() method and use Ds.tables[0].select("name='kapil'");

It will do the same things


Thanks
Umesh Bhosale



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: