Read and Write XML file used LINQ in C#

18 October 2023 | Viewed 1231 times

XLinq is . NET Language Integrated Query for XML Data

It takes advantage of the Standard Query Operators and adds query extensions specific to XML.

From an XML perspective XLinq provides the query and transformation power of XQuery and XPath integrated into .NET Framework languages that implement the LINQ pattern (e.g., C#, VB, etc.).

This provides a consistent query experience across LINQ enabled APIs and allows you to combine XML queries and transforms with queries from other data sources.

Reading data from xml file

C# Code
protected void Get_Click(object sender, EventArgs e)
{
XElement Names = XElement.Load(Server.MapPath(@"~/App_Data/Names.xml"));

//To retrieve Elemnts from XML file
var names = from CH in Names.Elements("Name")
select new
{
FN = CH.Element("FN").Value,
LN = CH.Element("LN").Value,
Age = CH.Attribute("Age").Value
};

GridView1.DataSource = names;
GridView1.DataBind();
}

Inserting records into an xml file

C# Code
protected void Add_Click(object sender, EventArgs e)
{
XDocument Names = XDocument.Load(Server.MapPath(@"~/App_Data/Names.xml"));

//To add new Element to XML file
Names.Element("Names").Add(
new XElement("Name",
new XElement("FN", "Cherukuri"),
new XElement("LN", "Venkateswarlu"),
new XAttribute("Age", "25")));

Names.Save(Server.MapPath(@"~/App_Data/Names.xml"));
}

Updateing record in an xml file

C# Code
protected void Update_Click(object sender, EventArgs e)
{
XDocument Names = XDocument.Load(Server.MapPath(@"~/App_Data/Names.xml"));

// To update XML elements
foreach (XElement xe in Names.Elements("Names").Elements())
{
if (xe.Element("FN").Value == "Cherukuri")
{
xe.Element("LN").SetValue("Venky");
xe.Attribute("Age").SetValue("26");
}
}

Names.Save(Server.MapPath(@"~/App_Data/Names.xml"));
}

Deleting record from an xml file

C# Code
protected void Delete_Click(object sender, EventArgs e)
{
XDocument Names = XDocument.Load(Server.MapPath(@"~/App_Data/Names.xml"));

foreach (XElement xe in Names.Elements("Names").Elements())
{
// To remove Element from XML
if (xe.Element("FN").Value == "Cherukuri")
{
xe.Remove();
}
// To remove attribute for XML Element
if (xe.Attribute("Age").Value == "25")
{
xe.Attribute("Age").Remove();
}
}
Names.Save(Server.MapPath(@"~/App_Data/Names.xml"));
}


Sample XML file:
<Names>
<Name Age="26">
<FN>Venkat</FN>
<LN>Cherukuru</LN>
</Name>
</Names>

Previous