Wednesday, February 17, 2010

Xml Manipulation Using Linq-Some basic lessons

The “functional construction” feature of Linq to Xml provides great usability in creating and modifying xml documents. XDocument object is used for the xml declarations. The XElement class constructor are used in resolving the xml entities.

string path = Server.MapPath(@"/Linq2XML/DataStore.xml");
XDocument xd = XDocument.Load(path);
var result = from c in xd.Elements("DataStore").Elements("Table") select new { oid = (string)c.Element("oid"), BuildName = (string)c.Element("BuildName"), Appserver = (string)c.Element("Appserver"), DBServerName = (string)c.Element("DBServerName"), dbname = (string)c.Element("DBName"), comments = (string)c.Element("comments") };

This will load the Xml file to your XDocument object and perform a linq operation to get the xml elements. We can use Descendants to return the filtered collection of matching XName elements.

For modifying the elements we can use the SetElementValue Method of XElement, that will set, add and remove child elements.

public void ModifyEnvironments(string oid,string buildName,string appServer,string dbServer,string dbName,string comments )
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
var items = from item in objdoc.Descendants("Table")
where item.Element("oid").Value == oid
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("BuildName", buildName);
itemElement.SetElementValue("Appserver", appServer);
itemElement.SetElementValue("DBServerName", dbServer);
itemElement.SetElementValue("DBName", dbName);
itemElement.SetElementValue("comments", comments);
}
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

We can use Remove() to delete an element.Also can use RemoveContent method that will make an empty element tag()

public void DeleteEnvironment(string oid)

{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
var items = (from item in objdoc.Descendants(@"Table")
where item.Element("oid").Value == oid
select item).FirstOrDefault();
items.Remove();
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
}

For adding new XElement we can use the Add() method

public void AddEnvironments(string buildName, string appServer, string dbServer, string dbName, string comments)
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
XElement xe = objdoc.Descendants("DataStore").Last();
xe.Add(new XElement("Table", new XElement("oid", GetMaxOid()), new XElement("BuildName", buildName)
,new XElement("Appserver",appServer),new XElement("DBServerName",dbServer),new XElement("DBName",dbName),
new XElement("comments",comments)));
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

Please find the sample XML file (“DataStore.xml”)here

0 comments: