Learning LINQ Made Easy (LINQ to XML): Tutorial 3

Introduction

This article is the next in the LINQ series to make the learning easy for beginners to get a clear understanding of the concepts. I have seen young developers and students that are very confused about LINQ and XML. This article will help them to understand and leverage their knowledge and to learn the advanced features later.

If you are new to LINQ then please have a look at the basic articles for LINQ.

Background

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework.

MSDN Says, LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.
It provides both DOM and XQuery/XPath like functionality in a consistent programming experience across the various LINQ-enabled data access technologies.

Functional construction

It is a way to create a XML tree using a single statement rather going for the traditional approach of DOM implementation.
There are certain classes that are used to create an XML tree with functional construction.

The following is LINQ to XML class hierarchy, I have copied this image from the MSDN to make the structure more clear.



The preceding diagram is from the MSDN.

There are many more classes that can be used in LINQ to XML. The following are a few of them to explain the functional construction of XML.

  • XDocument
  • XDeclaration
  • XComment
  • XElement
  • XAttribute

CustomersDetail.xml

  1. <?xml version="1.0" encoding="utf-8" standalone="yes"?> (XDeclaration)  
  2.    <!--LINQ to XML Demo--> (XComment)  
  3.    <Customers> (XElement)  
  4.       <Customer CustID="1001">(CustID = XAttribute)  
  5.       <Name>Abhishek</Name>  
  6.       <MobileNo>9820098200</MobileNo>  
  7.       <Location>Mumbai</Location>  
  8.       <Address>off link road Malad west Mumbai</Address>  
  9.    </Customer>  
  10.    <Customer CustID="1002">  
  11.       <Name>Rajesh</Name>  
  12.       <MobileNo>9820011234</MobileNo>  
  13.       <Location>New Delhi</Location>  
  14.       <Address>off link road laljatnagar New Delhi</Address>  
  15.    </Customer>  
  16.    <Customer CustID="1003">  
  17.       <Name>Rohan</Name>  
  18.       <MobileNo>9820022200</MobileNo>  
  19.       <Location>Mumbai</Location>  
  20.       <Address> link road Kandivali west Mumbai</Address>  
  21.    </Customer>  
  22.    <Customer CustID="1004">  
  23.       <Name>Sonali</Name>  
  24.       <MobileNo>9820098200</MobileNo>  
  25.       <Location>Mumbai</Location>  
  26.       <Address>khar west Mumbai</Address>  
  27.    </Customer>  
  28. </Customers> 

Sample Code

This is sample code for the functional construction of XML using LINQ to XML with a statement. I have hard coded the values here just to explain the structure and classes used.

  1. namespace LINQ_Learning  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             XDocument xmlDocument = new XDocument(  
  8.                 new XDeclaration("1.0","utf-8","yes"),  
  9.   
  10.                 new XComment("LINQ To XML Demo"),  
  11.   
  12.                 new XElement("Customers",  
  13.                     new XElement("Customer",new XAttribute("CustID",1001),  
  14.                         new XElement("Name","Abhishek"),  
  15.                         new XElement("MobileNo","9820098200"),  
  16.                         new XElement("Location","Mumbai"),  
  17.                         new XElement("Address","off link road malad west Mumbai")),  
  18.   
  19.                     new XElement("Customer",new XAttribute("CustID",1002),  
  20.                         new XElement("Name","Rajesh"),  
  21.                         new XElement("MobileNo","9820011234"),  
  22.                         new XElement("Location","New Delhi"),  
  23.                         new XElement("Address","off link road laljatnagar New delhi")),  
  24.   
  25.                     new XElement("Customer",new XAttribute("CustID",1003),  
  26.                         new XElement("Name","Rohan"),  
  27.                         new XElement("MobileNo","9820022200"),  
  28.                         new XElement("Location","Mumbai"),  
  29.                         new XElement("Address"," link road Kandivali  west Mumbai")),  
  30.   
  31.                     new XElement("Customer",new XAttribute("CustID",1004),  
  32.                         new XElement("Name","Sonali"),  
  33.                         new XElement("MobileNo","9820098200"),  
  34.                         new XElement("Location","Mumbai"),  
  35.                         new XElement("Address","khar west Mumbai"))  
  36.                         ));  
  37.   
  38.          xmlDocument.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  39.   
  40.          Console.ReadLine();             
  41.         }  
  42.     }  

The preceding example has hard-coded values just to explain how the functional construction works.

We can do that using in-memory objects or data from a database using ADO.Net or using the Entity Framework depending on your requirements.

Here I am explaining this using an in-memory object List.

Sample code

  1. namespace LINQ_Learning  
  2. {  
  3.    public class Customers  
  4.     {  
  5.         public int CustID { getset; }  
  6.         public string Name { getset; }  
  7.         public long MobileNo { getset; }  
  8.         public string Location { getset; }  
  9.         public string Address { getset; }  
  10.   
  11.         public static List<Customers> GetCostomersDetail()  
  12.         {  
  13.             List<Customers> lstcustomer = new List<Customers>()  
  14.             {  
  15.                 new Customers{CustID=10001,Name="Abhishek" , MobileNo=9820098200, Location="Mumbai",Address="off link road malad west Mumbai"},  
  16.                  new Customers{CustID=10001,Name="Rajesh" , MobileNo=9820011234, Location="New Delhi",Address="off link road laljatnagar New delhi"},  
  17.                   new Customers{CustID=10001,Name="Rohan" , MobileNo=9820011266, Location="Mumbai",Address="link road Kandivali  west Mumbai"},  
  18.                    new Customers{CustID=10001,Name="Abhishek" , MobileNo=890012452, Location="Mumbai",Address="khar west Mumbai"}  
  19.             };  
  20.   
  21.             return lstcustomer;  
  22.         }  
  23.     }  

Main Method

  1. namespace LINQ_Learning  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             XDocument xmlDocument = new XDocument(  
  8.                 new XDeclaration("1.0","utf-8","yes"),  
  9.   
  10.                 new XComment("LINQ To XML Demo"),  
  11.   
  12.                 new XElement("Customers",  
  13.                       
  14. from customers in Customers.GetCostomersDetail()  
  15.            select new XElement("Customer" , new XAttribute("ID" , customers.CustID),  
  16.                   new XElement("Name" , customers.Name),  
  17.                   new XElement("Mobile" , customers.MobileNo),  
  18.                   new XElement("Location" , customers.Location),  
  19.                   new XElement("Address" , customers.Address))  
  20.                           
  21.                  ));  
  22.             xmlDocument.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  23.   
  24.             Console.ReadLine();             
  25.         }  
  26.     }  

Querying using xml document using LINQ to XML

IEnumerable<T> can be used to query the XML data and for this standard query the operators show up as extension methods on any object that implements IEnumerable<T> and can be invoked like any other method.

  • Where
  • Select
  • SelectMany
  • OrderBy
  • GroupBy
  1. namespace LINQ_Learning  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.   
  8.           xmlDocument.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  9.   
  10.  IEnumerable<string> names = from customers in      
  11.                          XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml")  
  12.                                    .Descendants("Customer")  
  13.                         select customers.Element("Name").Value;  
  14.   
  15.             foreach(string strName in names)  
  16.             {  
  17.                 Console.WriteLine(strName);  
  18.             }  
  19.   
  20.             Console.ReadLine();             
  21.         }  
  22.     }  

Another way to do that

  1. namespace LINQ_Learning  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.   
  8.           xmlDocument.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  9.   
  10.                 IEnumerable<string> names = from customers in   
  11.                           XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml")  
  12.                                             .Element("Customers").Elements("Customer")  
  13.                                          
  14.                  select customers.Element("Name").Value;   
  15.             foreach(string strName in names)  
  16.             {  
  17.                 Console.WriteLine(strName);  
  18.             }  
  19.   
  20.             Console.ReadLine();             
  21.         }  
  22.     }  

Manipulating XML

LINQ to XML provides a full set of methods for manipulating XML including insert, delete, copy and update XML content.

Inserting new Element

Using the Add() method new elements can be added to the existing XML Tree.

  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2.   
  3. xdoc.Element("Customers").Add(  
  4.    new XElement("Customer" , new XAttribute("CustID", 1005),  
  5.    new XElement("Name","Jonn"),  
  6.    new XElement("MobileNo","992282760"),  
  7.    new XElement("Location","London"),  
  8.    new XElement("Address","34th streat London")  
  9. ));  
  10.   
  11. xdoc.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml"); 

If it is necessary to get the n elements added at the first element.

  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2. xdoc.Element("Customers").AddFirst(  
  3.    new XElement("Customer" , new XAttribute("CustID", 1000),  
  4.    new XElement("Name","Bob"),  
  5.    new XElement("MobileNo","9922823460"),  
  6.    new XElement("Location","London"),  
  7.    new XElement("Address","27th streat London")  
  8. ));  
  9.   
  10. xdoc.Save(@"C:\Dev\LINQ_Learning\CustomersDetail.xml"); 

There are two methods available if you want to add at a specific location.

  • AddAfterSelf
  • AddBeforeSelf
  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2. xdoc.Element("Customers").Elements("Customer")  
  3. .Where(X => X.Attribute("ID").Value == "10003").SingleOrDefault()  
  4. .AddBeforeSelf(  
  5.       new XElement("Customer"new XAttribute("CustID", 2000),  
  6.       new XElement("Name""David"),  
  7.       new XElement("MobileNo""9921123460"),  
  8.       new XElement("Location""London"),  
  9.       new XElement("Address""87th streat London")  
  10. )); 

Deleting XML

To delete XML, navigate to the content you want to delete and use the Remove() Method to perform the delete operation as in the following:

  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2.   
  3. xdoc.Root.Elements().Where(x => x.Attribute("ID").Value == "10002").FirstOrDefault().Remove(); 

Updating XML

XML Elements can be updated using the setElement Method.

  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2. xdoc.Element("Customers").Elements("Customer")  
  3. .Where(X => X.Attribute("ID").Value == "10002").SingleOrDefault()  
  4. .SetElementValue("Mobile", 9090909090); 

The ReplaceNodes() method can be used if nodes need to be replaced.

Validation of XML

XML can be validated using the XML Schema Definition (XSD) language.

XElement tree validation with an XML schema is done by importing the System.Xml.Schema namespace.

A XSD file will give you a schema file where user validations can be placed and that can be applied to XML data and the validation can be implemented.

On failure or success when validating there is a delegate provided that can use an error message and a customer error message can be printed.

Sample Code

  1. XDocument xdoc = XDocument.Load(@"C:\Dev\LINQ_Learning\CustomersDetail.xml");  
  2. XmlSchemaSet xmlSchema = new XmlSchemaSet();  
  3. xmlSchema.Add("", @"C:\Dev\LINQ_Learning\LINQ_Learning\XMLTest.xsd");  
  4. bool _ErrorMessage=false;  
  5.   
  6. xdoc.Validate(xmlSchema,(_sender,_args)=>  
  7. {  
  8.    Console.WriteLine(_args.Message);  
  9.    _ErrorMessage = true;  
  10. });  
  11.   
  12. if (_ErrorMessage)  
  13. {  
  14.    Console.WriteLine("Error While validating!!!!");  
  15. }  
  16. else  
  17. {  
  18.    Console.WriteLine("Successfully validating!!!!");  

A XSD file can be added from the Microsoft project templates.



There is an overloaded Add method provided for adding the schema files URI and target namespace.



The Validate method will accept a schema object and an event handler for validating the XML file against the XSD.



Output



Advantages of LINQ to XML

  • Load and Serialize XML from files or streams.
  • XML to files or streams.
  • Create XML trees from scratch using functional construction.
  • Query XML trees using LINQ queries.
  • Manipulate in-memory XML trees.
  • Validate XML trees using XSD.
  • Use a combination of these features to transform XML trees from one shape into another.

Conclusion

There are many advantages and disadvantages of using LINQ technology. It is very important to choose very intelligently the LINQ for your application so that beautiful features of LINQ to XML can be utilized and the application could be more efficient. It should not be a performance overhead and problem for your application.

More Tutorials on LINQ will be coming shortly.

Keep smiling and keep learning.

References: https://msdn.microsoft.com/en-us/library/bb308960.aspx

Next Recommended Readings