LINQ - XML



LINQ to XML offers easy accessibility to all LINQ functionalities like standard query operators, programming interface, etc. Integrated in the .NET framework, LINQ to XML also makes the best use of .NET framework functionalities like debugging, compile-time checking, strong typing and many more to say.

Introduction of LINQ to XML

While using LINQ to XML, loading XML documents into memory is easy and more easier is querying and document modification. It is also possible to save XML documents existing in memory to disk and to serialize them. It eliminates the need for a developer to learn the XML query language which is somewhat complex.

LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19 necessary classes to work with XML. These classes are the following ones.

  • XAttribute
  • XCData
  • XComment
  • XContainer
  • XDeclaration
  • XDocument
  • XDocumentType
  • XElement
  • XName
  • XNamespace
  • XNode
  • XNodeDocumentOrderComparer
  • XNodeEqualityComparer
  • XObject
  • XObjectChange
  • XObjectChangeEventArgs
  • XObjectEventHandler
  • XProcessingInstruction
  • XText

Read an XML File using LINQ

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace LINQtoXML {
   class ExampleOfXML {
      static void Main(string[] args) {
      
         string myXML = @"<Departments>
                       <Department>Account</Department>
                       <Department>Sales</Department>
                       <Department>Pre-Sales</Department>
                       <Department>Marketing</Department>
                       </Departments>";

         XDocument xdoc = new XDocument();
         xdoc = XDocument.Parse(myXML);

         var result = xdoc.Element("Departments").Descendants();

         foreach (XElement item in result) {
            Console.WriteLine("Department Name - " + item.Value);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq

Module Module1

   Sub Main(ByVal args As String())
   
      Dim myXML As String = "<Departments>" & vbCr & vbLf & 
                           "<Department>Account</Department>" & vbCr & vbLf & 
                           "<Department>Sales</Department>" & vbCr & vbLf & 
                           "<Department>Pre-Sales</Department>" & vbCr & vbLf & 
                           "<Department>Marketing</Department>" & vbCr & vbLf & 
                           "</Departments>"

      Dim xdoc As New XDocument()
      xdoc = XDocument.Parse(myXML)

      Dim result = xdoc.Element("Departments").Descendants()

      For Each item As XElement In result
         Console.WriteLine("Department Name - " + item.Value)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub
   
End Module

When the above code of C# or VB is compiled and executed, it produces the following result −

Department Name - Account
Department Name - Sales
Department Name - Pre-Sales
Department Name - Marketing

Press any key to continue. 

Add New Node

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace LINQtoXML {
   class ExampleOfXML {
      static void Main(string[] args) {
      
         string myXML = @"<Departments>
                       <Department>Account</Department>
                       <Department>Sales</Department>
                       <Department>Pre-Sales</Department>
                       <Department>Marketing</Department>
                       </Departments>";

         XDocument xdoc = new XDocument();
         xdoc = XDocument.Parse(myXML);

         //Add new Element
         xdoc.Element("Departments").Add(new XElement("Department", "Finance"));

         //Add new Element at First
         xdoc.Element("Departments").AddFirst(new XElement("Department", "Support"));

         var result = xdoc.Element("Departments").Descendants();

         foreach (XElement item in result) {
            Console.WriteLine("Department Name - " + item.Value);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq

Module Module1

   Sub Main(ByVal args As String())
   
      Dim myXML As String = "<Departments>" & vbCr & vbLf & 
     	                   "<Department>Account</Department>" & vbCr & vbLf & 
     	                   "<Department>Sales</Department>" & vbCr & vbLf & 
     	                   "<Department>Pre-Sales</Department>" & vbCr & vbLf & 
     	                   "<Department>Marketing</Department>" & vbCr & vbLf & 
     	                   "</Departments>"

      Dim xdoc As New XDocument()
      xdoc = XDocument.Parse(myXML)

      xdoc.Element("Departments").Add(New XElement("Department", "Finance"))
     
      xdoc.Element("Departments").AddFirst(New XElement("Department", "Support"))

      Dim result = xdoc.Element("Departments").Descendants()

      For Each item As XElement In result
         Console.WriteLine("Department Name - " + item.Value)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub
   
End Module

When the above code of C# or VB is compiled and executed, it produces the following result −

Department Name - Support
Department Name - Account
Department Name - Sales
Department Name - Pre-Sales
Department Name - Marketing
Department Name - Finance

Press any key to continue.

Deleting Particular Node

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace LINQtoXML {
   class ExampleOfXML {
      static void Main(string[] args) {
      
         string myXML = @"<Departments>
                       <Department>Support</Department>
                       <Department>Account</Department>
                       <Department>Sales</Department>
                       <Department>Pre-Sales</Department>
                       <Department>Marketing</Department>
                       <Department>Finance</Department>
                       </Departments>";

         XDocument xdoc = new XDocument();
         xdoc = XDocument.Parse(myXML);

         //Remove Sales Department
         xdoc.Descendants().Where(s =>s.Value == "Sales").Remove(); 

         var result = xdoc.Element("Departments").Descendants();

         foreach (XElement item in result) {
            Console.WriteLine("Department Name - " + item.Value);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq

Module Module1

   Sub Main(args As String())
   
      Dim myXML As String = "<Departments>" & vbCr & vbLf & 
     	                   "<Department>Support</Department>" & vbCr & vbLf & 
     	                   "<Department>Account</Department>" & vbCr & vbLf & 
     	                   "<Department>Sales</Department>" & vbCr & vbLf & 
     	                   "<Department>Pre-Sales</Department>" & vbCr & vbLf & 
     	                   "<Department>Marketing</Department>" & vbCr & vbLf & 
     	                   "<Department>Finance</Department>" & vbCr & vbLf & 
                           "</Departments>"

      Dim xdoc As New XDocument()
      xdoc = XDocument.Parse(myXML)
     
      xdoc.Descendants().Where(Function(s) s.Value = "Sales").Remove()

      Dim result = xdoc.Element("Departments").Descendants()

      For Each item As XElement In result
         Console.WriteLine("Department Name - " + item.Value)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub
   
End Module

When the above code of C# or VB is compiled and executed, it produces the following result −

Department Name - Support
Department Name - Account
Department Name - Pre-Sales
Department Name - Marketing
Department Name - Finance

Press any key to continue. 
Advertisements