Home » LINQ to XML

LINQ to XML

It is a programming interface that enables us to write the LINQ Queries on XML documents to get the required data.

The LINQ to XML will bring the XML document into memory and allows us to write LINQ Queries on in-memory XML document to get the XML document elements and attributes.

To use LINQ to XML functionality in our applications, we need to add “System.Xml.Linq” namespace reference.

Syntax of LINQ to XML

Here is the syntax of writing the LINQ Queries on XML data.

From the above syntax, we are reading the data of the xml file and writing the LINQ queries to get the required data from XML.

LINQ to XML Example

Now we will see how to use XML with LINQ Queries in asp.net web application with example. To create the application, we have to follow the following steps. Open Visual Studio->Go to File-> Select New->Select project as shown below.

LINQ To XML

After selecting the project, a new popup will open. From there we have to select “Asp.Net Empty Web Application” give the name as “LINQtoXML” and click “OK” button as shown below:

LINQ To XML 1

To work with LINQ and XML, we will add one XML file in our application. For that, we will right-click on the application-> Select Add-> Select New Item, as shown below:

LINQ To XML 2

After clicking on the new item, a new popup will open in that select XML file from the Data Section → Give a name to the XML File->Click Add button, as shown below.

LINQ To XML 3

When the file is added, we will open it and add the some record as shown below:

Now we will show “XMLFile.xmldata in our application. For that, we have to right click on the application→Select Add->New Item->Select Web Form->Give name as Default1.aspx and click “OK” button.

Now open “Default1.aspx” page and write the code like as shown below:

Now open the code behind the file and write the following code:

If we observe the above example, we added the namespace like “System.Xml.Linq” it will allow us to read the xml document data, and we can write the condition on XML data to get the records where “Salary” greater than equal to ?2000?.Now we will run and see the result of the application.

OUTPUT

LINQ To XML 4


Next Topic#

You may also like