Getting Started with LINQ to XML in C#

c fopenExtensible Markup Language (XML) is one of the simplest ways to represents complex information that has to be transferred on the web. It is platform independent which makes it a good solution to share same data across different technologies like Web, Desktop and mobile. In C#, .NET framework provides different ways to read/write XML data. Some important ones are ‘XMLTextReader’, ‘XMLSerializer’, ‘XMLDocument’ and Language Integrated Query ‘LINQ’ to ‘XML’. ’LINQ’ is a set of features to extend the query capability of the C# language

What is LINQ to XML?

LINQ to XML is a set of .NET framework classes residing in ‘System.Xml.Linq’ namespace used to create, update, delete and query data from XML document, the ‘XDocument’ class.

How LINQ to XML works?

In LINQ to XML, just like Document Object Model (DOM), before performing any operations, the XML document is brought into the memory. The integrated LINQ is used to write queries on that in memory XML document, which returns nodes or the subset of nodes.

To learn more about C# LINQ, check out a course at Udemy.com.

Create XML using LINQ to XML

‘Functional Construction’ is the simplest LINQ to XML approach that is used to create a XML file. In this approach, the queried results for LINQ to XML are used in the constructors of ‘XElement’ and ‘XAttribute’ objects to create and transform the XML trees. Following code snippets demonstrates the creation of XML document using the functional construction.

Code Snippet 1, to Create a Book Class:

public class Book

{

public int ID { get; set; }

public string Name { get; set; }

public string Version { get; set; }

public int YearOfPublish { get; set; }

}

Code snippet 2, to create XML document:

Book[] allBooks = new Book[] {

new Book { ID = 1, Name = "Getting Started with C#", Version = "1.2", YearOfPublish = 1999},

new Book { ID = 2, Name = "Introduction to C#", Version = "2.0", YearOfPublish = 2004},

new Book { ID = 3, Name = "Advanced Features of C#", Version = "4.0", YearOfPublish = 2014},

};

XDocument document = new XDocument

(

new XDeclaration ( "1.0", "utf-8", "yes" ),

new XElement ("Books",

from book in allBooks

select new XElement ( "Book", new XAttribute("ID", book.ID ),

new XElement ( "Name", book.Name ),

new XElement ( "Version", book.Version ),

new XElement ( "YOP", book.YearOfPublish ) )

)

);

document.Save ("C:/Book.xml");

In the above code snippet ‘Book’ class objects are saved to XML document using queried results from ‘Book’ objects array. The ‘XElement’ represents a root element of document or child elements of the root while ‘XAttribute’ represents the attribute of an element. In the above snippet of LINQ to XML, ‘XElement’ object (root node ‘Books’) of ‘XDocument’ is used with LINQ queried data to create the child elements (‘book’) with attribute ‘ID’ and child nodes ‘Name’, ‘Version’ and ‘YOP’, which is then saved in ‘Book.xml’ file using ‘document.save’ method. Following is the stripped output of above code snippet.

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<Books>

<Book ID="1">

<Name>Getting Started with C#</Name>

<Version>1.2</Version>

<YOP>1999</YOP> </Book> </Books>

For more interesting C# tutorials, check out courses at Udemy.com.

Read XML using LINQ to XML

Reading XML document content using LINQ to XML, first includes loading of document in a memory then the extension method of LINQ to XML is used to returns a collection of nodes. Finally this collection is queried using LINQ. Following examples demonstrate the use of extensions method and LINQ queries.

Code snippet ‘1’

XElement xelement = XElement.Load ("C:/Book.xml");

IEnumerable<XElement> books = xelement.Elements ();

Code snippet ‘2’

IEnumerable <XElement> Books = (from book in

XDocument.Load ("C:/Book.xml")

.Descendants ("Books") select book)

.ToArray ();

Code snippet ‘3’

XElement xelement = XElement.Load ("C:/Book.xml");

IEnumerable <XElement> Books = (from book in xelement.Elements ("Book")

where (int) book.Element ("YOP") == 2014

select book )

.ToArray ();

In the above code snippets ‘1’ and ‘2’, all elements of XML document are read. In first snippet ‘Load’ method is called with ‘XElement’ object which returns a root node of the document then on root an extension method ‘Elements’ of LINQ to XML is called which returns all the child elements of the root in a collection of ‘XElement’.

In second snippet, the LINQ query is used where ‘XDocument’ loads an XML document to memory then an extension method ‘Descendants’ is called which returns the root node of XML to a query. Finally, ‘Select’ keyword is used which specify the returned elements (in this case all the root node elements).

In third snippet, a LINQ query is used to retrieve the book elements thatare published in year ‘2014’. At the start of a code snippet ‘3’, an XML document is loaded with ‘XElement’ object then in the LINQ query an extension method ‘Elements’ returns all the elements having names, ‘Book’. A ‘where’ keyword is used to query out the books which are published in ‘2014’. And in the last line, ‘select’ keyword specifies these retrieved elements as a resultant of a query.

Insert element using LINQ to XML

To insert a new element using LINQ to XML requires loading XML document to the memory, afterwards a call of ‘Element’ method is executed on ‘XDocument’ object to get first element of the document identified by its name as an argument. In the end an ‘Add’ method is required to call on a returned ‘XElement’ object with a new ‘XElement’ object as an argument. Following code snippet demonstrates the discussed process for inserting a new element in XML.

Code snippet:

XDocument document = XDocument.Load ("C:/Book.xml");

document.Element ("Books").Add (

new XElement ("Book", new XAttribute("ID", 4),

new XElement ("Name", "C# for Novice User"),

new XElement ("Version", "1.0"),

new XElement ("YOP", 2007)

)

);

document.Save ("C:/Book.xml");

Update element using LINQ to XML

To update a XML element using LINQ to XML, first an element attribute or sub-child is queried out from all of the elements using LINQ then a ‘SetValue’ method of ‘XElement’ or ‘XAttribute’ is called to set a new value. Following example demonstrates this concept:

Code snippet

document.Element ("Books").Elements ()

.Where (e => e.Element ("Name").Value.Equals ("C# for Novice User"))

.Select (e => e.Element ("Version"))

.Single ()

.SetValue ("1.2");

document.Save ("C:/Book.xml");

Delete element using LINQ to XML

To delete a XML element using LINQ to XML, an element is queried out from all of the elements with ‘where’ keyword then a ‘Remove’ method of ‘XElement’ is called to remove the queried element. Following example removes the specific book queried by “ID”.

Code snippet:

document.Element ("Books").Elements ()

.Where (e => e.Attribute ("ID").Value.Equals ("4"))

.Select (e => e)

.Single ()

.Remove ();

document.Save ("C:/Book.xml");

To learn more about essentials of C#, take a course at Udemy.com.