XLINQ Operations
To use XLINQ objects we need to import the following dll.
System.Xml.Linq
XLinq
. NET Language Integrated Query for XML Data
XLinq was developed with Language Integrated Query over XML in mind from the beginning.
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.
Code to delete records from an xml file by using XLINQ objects
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.Attribute("Age").Value == "25")
{
xe.Remove();
}
// To remove attribute for XML Element
if (xe.Element("FN").Value == "Cherukuri")
{
xe.Attribute("Age").Remove();
}
}
Names.Save(Server.MapPath(@"~/App_Data/Names.xml"));
}
Code to update records in an xml file by using XLINQ objects
protected void Update_Click(object sender, EventArgs e)
{
XDocument Names = XDocument.Load(Server.MapPath(@"~/App_Data/Names.xml"));
// To updating 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"));
}
Code to insert records into an xml file by using XLINQ objects
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"));
}
Code to retrieve records from an xml file by using XLINQ objects
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();
}