Processing XML using LINQ
By Mash B
As a developer in many concepts we come across
parsing of xml document such as reading it , Search For Particular Attribute Value in it and get the data
or creating the xml etc. In such scenario we always end up with writing junk of complicated code and sometimes
its hard for the analyzer who analyzes the code.
The purpose of writing this article is , as a developer in many concepts we come
across
parsing of xml document such as reading it , Search For Particular Attribute Value
in it and get the data
or creating the xml etc. In such scenario we always end up with writing junk of complicated
code and sometimes
its hard for the analyzer who analyzes the code.
So in below article i would like to demonstrate how easily we can process , parse
the xml document using LINQ to XML.
Below is the xml snippet i'm going to refer throughout my examples which is named
as "Employees.xml"
<?xml version="1.0" encoding="ISO-8859-1"?>
<Employees>
<person>
<id>1</id>
<firstname>ABC</firstname>
<lastname>egg</lastname>
<idrole>1</idrole>
</person>
<person>
<id>2</id>
<firstname>XYZ</firstname>
<lastname>Head</lastname>
<idrole>2</idrole>
</person>
<!--Role section-->
<role>
<id>1</id>
<roledescription>Manager</roledescription>
</role>
<role>
<id>2</id>
<roledescription>Developer</roledescription>
</role>
<!--Salary section-->
<salary>
<idperson id="1" year="2004" salaryyear="10000,0000"
/>
<idperson id="1" year="2005" salaryyear="15000,0000"
/>
</salary>
</Employees>
Now to start with the LINQ to XML , you must have the following namespace included
using System.Linq;
using System.Xml.Linq;
using System.Xml;
Below shows the classes in System.XMl.linq , so that we dont get mixed up with System.Xml
classes
SySteM.XMl.linQ CLaSS SySteM.XMl CLaSS
XDocument XmlDocument
XElement XmlElement
XAttribute XmlAttribute
XNode XmlNode
XName No equivalent; uses strings or XmlNameTables
XNamespace No equivalent; uses XmlNameTables
XCData XmlCDataSection
XText XmlText
Below i have demonstrated some functions which we need in day to day logic
1) READING OF XML FILE
private static void ReadXML()
{
// Load the xml document from the specified path
XDocument xdoc = XDocument.Load(@"..\..\Employees.xml");
// Below LINQ query reads all the person under the Employees root tag
var query = from p in xdoc.Elements("Employees").Elements("person")
select p;
//Now loop through all the persons in resultset
foreach (var record in query)
{
string firstName = record.Element("firstname").Value;
string lastname = record.Element("lastname").Value;
string idrole = record.Element("idrole").Value;
}
}
2) READING RECORD FOR PERTICULAR PERSON ROLE ID
private static void SearchPersonInXML()
{
// Load the xml document from the specified path
XDocument xdoc = XDocument.Load(@"..\..\Employees.xml");
// Below LINQ query reads all the person under the Employees root tag
var query = from p in xdoc.Elements("Employees").Elements("person")
where (int)p.Element("idrole") == 1
// be careful with this statement, make sure you always
//typecast attribute when you are comparing else it will through exception
select p;
//Now loop through all the persons which is having roleid=1
foreach (var record in query)
{
string firstName = record.Element("firstname").Value;
string lastname = record.Element("lastname").Value;
string idrole = record.Element("idrole").Value;
}
}
3) SEARCHING FOR PARTICULAR ATTRIBUTE VALUE
private static void SearchingForAttributeValue()
{
XElement xml = XElement.Load(@"..\..\Employees.xml");
var query = from s in
xml.Elements("salary").Elements("idperson")
where (int)s.Attribute("year") == 2004
select s;
foreach (var record in query)
{
string amount = (string) record.Attribute("salaryyear");
}
}
4) DESCENDS METHOD TO NAVIGATE DOWN THE XML ELEMENTS
From above xml if we want to retrive the salary of person for particular role
private static void DescendsNavigateMethod()
{
XElement xml = XElement.Load(@"..\..\Employees.xml");
// Below i have performed join operation to extract salary for person role
var query = from p in xml.Descendants("person")
join s in xml.Descendants("idperson")
on (int)p.Element("id") equals (int)s.Attribute("id")
select new
{
FirstName = p.Element("firstname").Value,
LastName = p.Element("lastname").Value,
Amount = s.Attribute("salaryyear").Value
};
foreach(var record in query)
{
string FirstName = record.FirstName;
string LastName = record.LastName;
string Amount = record.Amount;
}
}
5) DELETE THE NODE BASED ON PARTICULAR ID
private static void DeleteNodeMethods()
{
XDocument doc = XDocument.Load(@"..\..\Employees.xml");
doc.Descendants("person").Where(x => x.Element("id").Value == "1").Single().Remove();
doc.Save("Your path to save");
}
6) MODIFY THE PARTICULAR ELEMENT IN XML DOCUMENT AND SAVE IT
private static void ModifyElement()
{
XElement page = XElement.Load(@"..\..\Employees.xml");
XElement modifyPerson = page.Elements("person").Where(es => (string)es.Element
("id") == "2").FirstOrDefault();
if (modifyPerson == null) return;
modifyPerson.SetElementValue("firstname", "this is the new name");
modifyPerson.SetElementValue("lastname", "this is the new last name");
modifyPerson.SetElementValue("idrole", "this is the role");
page.Save("Your Path");
}
7) RETRIVING COMMENTS FROM XML
private static void RetriveXMLComments()
{
XElement xml = XElement.Load(@"..\..\Employees.xml");
IEnumerable<XComment> record = xml.Nodes().OfType<XComment>();
foreach (XComment comment in record)
string commentsFromXml = comment;
}
Popularity (2871 Views)
Article Discussion: Processing XML using LINQ
Mash B posted at Thursday, June 17, 2010 3:34 AM