Naveen's Weblog

Bridge to future

LINQ to XML basic sample

Posted by codingsense on September 22, 2008


The Microsoft definition:

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

The namespace for dealing with XML is System.Xml.Linq

Download Sample – 26.4Kb

Basic Sample of LINQ to XML:

In this sample we will concentrate on how a XML can be created and accessed.
We will create a XML which will hold the client Information’s (ID,Name,Address).

Create a XML element:

XElement ClientInfo = new XElement("Clients",
new XElement("Client",
new XElement("ID", "1"),
new XElement("Name", "Client1"),
new XElement("Address", "Mahalaxmi")
),
new XElement("Client",
new XElement("ID", "2"),
new XElement("Name", "Client2"),
new XElement("Address", "J.C.Road")
),
new XElement("Client",
new XElement("ID", "3"),
new XElement("Name", "Client3"),
new XElement("Address", "M.G.Road")
)
);

Here XElement is an element of XML. It can be a single element or a child of another element or a parent with many more elements within it.

Output:

Only Client ID’s in a string Array::

Now lets try to take only client ID’s in a string array. Here is the code

string[] OnlyIDArr = (from Client in ClientInfo.Elements()
                      select Client.Element("ID").Value).ToArray<string>();

Output:

Create XML with only Client ID’s::

Here we will try to create an XML of only client ID’s

var OnlyID = from Client in ClientInfo.Elements()
             select new XElement("Client", Client.Element("ID"));

Output:

Nowadays XML is playing a vital role in many softwares and LINQ can be utilised to make it much easy, so try to explore it.

Keep Learning 🙂

Advertisements

One Response to “LINQ to XML basic sample”

  1. vijay said

    Nice Examples …..very useful information,thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: