LINQ to XML

  Total Views : 136
  Comments : 0
 
  Keywords : Linq to xml in asp.net using c# / vb.net with examples, Linq to xml to add new element / remove element / save changes to xml document in c# / vb.net with examples

Here we will learn LINQ to XML in c#, vb.net with example and how to use LINQ to XML to write queries on xml document like add new element to xml, remove element from xml, add number of elements from xml, save changes to xml document in c#, vb.net with examples.

LINQ to XML

LINQ to XML is a programming interface which enable us to write LINQ queries on XML documents to get required data.

 

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

 

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

Syntax of LINQ to XML

Following is the syntax of writing LINQ queries on XML data.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

var result = from ed in doc.Descendants("employee")

select new

{

Id = ed.Element("empid").Value,

Name = ed.Element("empname").Value

};

VB.NET Code

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

Dim result = From ed In doc.Descendants("employee") Select New With {.Id = ed.Element("empid").Value, .Name = ed.Element("empname").Value}

If you observe above syntax we are reading xml file data and writing LINQ queries to get 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 application, follow below steps.

Open visual studio --> Go to File --> Select New --> Select Project like as shown below

 

Create new linq to xml project in visual studio

 

Once we select project new pop up will open in that select Asp.Net Empty Web Application then give name as “LINQtoXML” and click OK button like as shown below

 

create new asp.net empty web application for linq to xml example To work with LINQ and XML we will add one XML file in our application for that right click on your application --> select Add --> select New Item like as shown below

 

Add new item to LINQ to XML Application in C# / VB.NET

 

 Once we click on New Item new pop up will open in that select XML file from Data section --> Give name for that xml file --> Click Add button like as shown below

 

Add new xml file to linq to xml application in c#, vb.net

 

Once we add xml file open it and add some records like as shown below

 

<?xmlversion="1.0"encoding="utf-8" ?>

<Employees>

<employee>

<empid>1</empid>

<empname>Suresh Dasari</empname>

<salary>10000</salary>

<gender>Male</gender>

</employee>

<employee>

<empid>2</empid>

<empname>Rohini Alavala</empname>

<salary>20000</salary>

<gender>Female</gender>

</employee>

<employee>

<empid>3</empid>

<empname>Praveen Alavala</empname>

<salary>30000</salary>

<gender>Male</gender>

</employee>

<employee>

<empid>4</empid>

<empname>Sateesh Chandra</empname>

<salary>50000</salary>

<gender>Male</gender>

</employee>

<employee>

<empid>5</empid>

<empname>Sushmitha</empname>

<salary>60000</salary>

<gender>Female</gender>

</employee>

</Employees>

Now we will show EmployeeDetail xml data in our application for that Right click on application --> select Add --> New Item --> Select Web Form --> Give name as Default.aspx and click OK button.

 

Now open Default.aspx page and write the code like as shown below

 

Default.aspx

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Bind Gridview with XML File Data</title>

<style type="text/css">

.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}

.headerstyle

{

color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color: #df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;

}

</style>

</head>

<body>

<form id="form1" runat="server">

<div class="GridviewDiv">

<asp:GridView ID="gvDetails" runat="server">

<HeaderStyle CssClass="headerstyle" />

</asp:GridView>

</div>

</form>

</body>

</html>

Now open code behind file and write following code in page load

 

C# Code

 

using System;

using System.Linq;

using System.Web.UI;

using System.Xml.Linq;

 

namespace LINQtoXML

{

public partial class Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

var result = from ed in doc.Descendants("employee")

where Convert.ToInt32(ed.Element("salary").Value) >= 20000

select new

{

Id = ed.Element("empid").Value,

Name = ed.Element("empname").Value,

Salary = ed.Element("salary").Value,

Gender = ed.Element("gender").Value

};

gvDetails.DataSource = result;

gvDetails.DataBind();

}

}

}

}

VB.NET Code

 

Imports System.Linq

Imports System.Web.UI

Imports System.Xml.Linq

 

Public Class WebForm1

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

If Not Page.IsPostBack Then

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

Dim result = From ed In doc.Descendants("employee") Where Convert.ToInt32(ed.Element("salary").Value) >= 20000 Select New With {.Id = ed.Element("empid").Value, .Name = ed.Element("empname").Value, .Salary = ed.Element("salary").Value, .Gender = ed.Element("gender").Value}

gvDetails.DataSource = result

gvDetails.DataBind()

End If

End Sub

End Class

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

Output of LINQ to XML Example

Following is the result of LINQ to XML example.

 

LINQ to XML Example Result or Output

 

We will learn some more code snippets in LINQ to XML to get required data from XML documents.

LINQ to XML Add New Element

Following is the code snippet to add new element to XML file dynamically using LINQ to XML.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

doc.Add(new XElement("employee",

new XElement("empid", 6),

new XElement("empname", "Madhav Sai"),

new XElement("salary", 80000),

new XElement("gender", "Male")));

VB.NET Code

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

doc.Add(New XElement("employee",

NewXElement("empid", 6),

NewXElement("empname", "Madhav Sai"),

NewXElement("salary", 80000),

NewXElement("gender", "Male")))

If you observe above code snippet we are adding new element to XML file dynamically using LINQ to XML.

LINQ to XML Add Element as First Child of XML File

Following is the syntax of adding new element as first child of XML file using LINQ to XML.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

doc.AddFirst(new XElement("employee",

new XElement("empid", 7),

new XElement("empname", "Honey"),

new XElement("salary", 90000),

new XElement("gender", "Female")));

VB.NET Code

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

doc.AddFirst(New XElement("employee",

NewXElement("empid", 6),

NewXElement("empname", "Madhav Sai"),

NewXElement("salary", 80000),

NewXElement("gender", "Male")))

If you observe above code snippet it will add element at first position of XML file.

LINQ to XML Remove Element in XML File

Following is the syntax of removing element in XML file using LINQ to XML.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

doc.Descendants("employee").Elements("empname").Where(x => x.Value == "Sushmitha").Remove();

VB.NET Code

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

doc.Descendants("employee").Elements("empname").Where(Function(x) x.Value = "Sushmitha").Remove()

If you observe above code snippet we are deleting element in xml file based on “empname”.

Remove 'n' Number of Elements using LINQ to XML

Following is the syntax of removing one or two or three elements from xml file using LINQ to XML based on our requirement.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

doc.Descendants("employee").Take(2).Remove();

VB.NET Code

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

doc.Descendants("employee").Take(2).Remove()

If you observe above syntax we are deleting first “2” elements from the XML file using LINQ.

Save / Persist XML Changes using LINQ to XML

Till now we did lot of changes to XML file using different methods but nothing is effecting XML file because those changes were in memory not changed in the XML file. If we want to make our changes reflect in XML file we need to call Save() method at the end of our modifications then only our changes will reflect in XML file.

 

C# Code

 

XElement doc = XElement.Load(Server.MapPath("EmployeeDetails.xml"));

doc.Add(new XElement("employee",

new XElement("empid", 6),

new XElement("empname", "Madhav Sai"),

new XElement("salary", 90000),

new XElement("gender", "Male")));

doc.Save(Server.MapPath("EmployeeDetails.xml"));

VB.NET

 

Dim doc As XElement = XElement.Load(Server.MapPath("EmployeeDetails.xml"))

doc.Add(New XElement("employee",

New XElement("empid", 6),

New XElement("empname", "Madhav Sai"),

New XElement("salary", 90000),

New XElement("gender", "Male")))

doc.Save(Server.MapPath("EmployeeDetails.xml"))

If you observe above code snippet we are adding new element to XML file and to persist new changes we are using Save method.

 

PREVIOUS

LINQ to Entities
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User