LINQ To XML Tutorials with Examples

Posted by: Suprotim Agarwal , on 8/29/2010, in Category LINQ
Views: 654661
Abstract: In this article, we will learn LINQ To XML using some ‘How Do I’ kind of examples.
A lot of developers over the past few months have requested us for tutorials focusing on LINQToXML. Although I have written a couple of them in the past, I decided to republish these tips in the form of a single post. In this article, we will explore 24 ‘How Do I’ kind of examples using LINQ to XML. I assume you are familiar with LINQ. If not, you can start off with LINQ by checking some tutorials over here and here.

 

For this article, we will be using a sample file called ‘Employees.xml’ for all our samples which is available with the source code. So make sure you keep it handy with you while are practicing these examples. The mark up for Employees.xml is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
 <Employee>
    <EmpId>1</EmpId>
    <Name>Sam</Name>   
    <Sex>Male</Sex>
    <Phone Type="Home">423-555-0124</Phone>
    <Phone Type="Work">424-555-0545</Phone>
   <Address>
      <Street>7A Cox Street</Street>
      <City>Acampo</City>
      <State>CA</State>
      <Zip>95220</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>2</EmpId>
    <Name>Lucy</Name>
    <Sex>Female</Sex>
    <Phone Type="Home">143-555-0763</Phone>
    <Phone Type="Work">434-555-0567</Phone>
    <Address>
      <Street>Jess Bay</Street>
      <City>Alta</City>
      <State>CA</State>
      <Zip>95701</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>3</EmpId>
    <Name>Kate</Name>
    <Sex>Female</Sex>
    <Phone Type="Home">166-555-0231</Phone>
    <Phone Type="Work">233-555-0442</Phone>
    <Address>
      <Street>23 Boxen Street</Street>
      <City>Milford</City>
      <State>CA</State>
      <Zip>96121</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
 <Employee>
    <EmpId>4</EmpId>
    <Name>Chris</Name>
    <Sex>Male</Sex>
    <Phone Type="Home">564-555-0122</Phone>
    <Phone Type="Work">442-555-0154</Phone>
    <Address>
      <Street>124 Kutbay</Street>
      <City>Montara</City>
      <State>CA</State>
      <Zip>94037</Zip>
      <Country>USA</Country>
    </Address>
 </Employee>
</Employees>
 
The application is a console application targeting .NET 3.5 framework, although you can use the latest .NET 4.0 framework too. I have also used ‘query expressions’, instead of Lambda expression in these samples. It is just a matter of preference and you are free to use any of these.
This tutorial has been divided into 2 sections:
Section 1: Read XML and Traverse the Document using LINQ To XML
Section 2: Manipulate XML content and Persist the changes using LINQ To XML
The following namespaces are needed while testing the samples: System; System.Collections.Generic; System.Linq; System.Text; System.Xml; System.Xml.Linq;
Go grab a hot cup of coffee, put on your developer cap and let us get started:
 
Section 1: Read XML and Traverse the XML Document using LINQ To XML
 
1. How Do I Read XML using LINQ to XML
There are two ways to do so: Using the XElement class or the XDocument class. Both the classes contain the ‘Load()’ method which accepts a file, a URL or XMLReader and allows XML to be loaded. The primary difference between both the classes is that an XDocument can contain XML declaration, XML Document Type (DTD) and processing instructions. Moreover an XDocument contains one root XElement.
Using XElement
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
    Console.WriteLine(employee);
}
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
' Read the entire XML
For Each employee In employees
      Console.WriteLine(employee)
Next employee
Output:
image_1
Using XDocument
C#
XDocument xdocument = XDocument.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xdocument.Elements();
foreach (var employee in employees)
{
    Console.WriteLine(employee);
}
 
VB.NET (Converted Code)
Dim xdocument As XDocument = XDocument.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xdocument.Elements()
For Each employee In employees
      Console.WriteLine(employee)
Next employee
Output:
image_11
Note 1: As you can observe, XDocument contains a single root element (Employees).
Note 2: In order to generate an output similar to the one using XElement, use  “xdocument.Root.Elements()” instead of  “xdocument.Elements()”
Note 3: VB.NET users can use a new feature called XML Literal.
 
2. How Do I Access a Single Element using LINQ to XML
Let us see how to access the name of all the Employees and list them over here
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
    Console.WriteLine(employee.Element("Name").Value);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
Console.WriteLine("List of all Employee Names :")
For Each employee In employees
      Console.WriteLine(employee.Element("Name").Value)
Next employee
Output:
image_2
3. How Do I Access Multiple Elements using LINQ to XML
Let us see how to access the name of all Employees and also list the ID along with it
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Employee Names along with their ID:");
foreach (var employee in employees)
{
    Console.WriteLine("{0} has Employee ID {1}",
        employee.Element("Name").Value,
        employee.Element("EmpId").Value);
}
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
Console.WriteLine("List of all Employee Names along with their ID:")
For Each employee In employees
      Console.WriteLine("{0} has Employee ID {1}", employee.Element("Name").Value, employee.Element("EmpId").Value)
Next employee
Output:
image_3
4. How Do I Access all Elements having a Specific Attribute using LINQ to XML
Let us see how to access details of all Female Employees
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var name = from nm in xelement.Elements("Employee")
           where (string)nm.Element("Sex") == "Female"
           select nm;
Console.WriteLine("Details of Female Employees:");
foreach (XElement xEle in name)
    Console.WriteLine(xEle);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim name = _
      From nm In xelement.Elements("Employee") _
      Where CStr(nm.Element("Sex")) = "Female" _
      Select nm
Console.WriteLine("Details of Female Employees:")
For Each xEle As XElement In name
      Console.WriteLine(xEle)
Next xEle
Output:
image_4
5. How Do I access Specific Element having a Specific Attribute using LINQ to XML
Let us see how to list all the Home Phone Nos.
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var homePhone = from phoneno in xelement.Elements("Employee")
                where (string)phoneno.Element("Phone").Attribute("Type") == "Home"
                select phoneno;
Console.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
    Console.WriteLine(xEle.Element("Phone").Value);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim homePhone = _
      From phoneno In xelement.Elements("Employee") _
      Where CStr(phoneno.Element("Phone").Attribute("Type")) = "Home" _
      Select phoneno
Console.WriteLine("List HomePhone Nos.")
For Each xEle As XElement In homePhone
      Console.WriteLine(xEle.Element("Phone").Value)
Next xEle
Output:
image_5
6. How Do I Find an Element within another Element using LINQ to XML
Let us see how to find the details of Employees living in 'Alta' City
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var addresses = from address in xelement.Elements("Employee")
                where (string)address.Element("Address").Element("City") == "Alta"
               select address;
Console.WriteLine("Details of Employees living in Alta City");
foreach (XElement xEle in addresses)
    Console.WriteLine(xEle);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim addresses = _
      From address In xelement.Elements("Employee") _
      Where CStr(address.Element("Address").Element("City")) = "Alta" _
      Select address
Console.WriteLine("Details of Employees living in Alta City")
For Each xEle As XElement In addresses
      Console.WriteLine(xEle)
Next xEle
Output:
image_26
7. How Do I Find Nested Elements (using Descendants Axis) using LINQ to XML
Let us see how to list all the zip codes in the XML file
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
Console.WriteLine("List of all Zip Codes");
foreach (XElement xEle in xelement.Descendants("Zip"))
{
    Console.WriteLine((string)xEle);
}
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Console.WriteLine("List of all Zip Codes")
For Each xEle As XElement In xelement.Descendants("Zip")
      Console.WriteLine(CStr(xEle))
Next xEle
Output:
image_37
8. How do I apply Sorting on Elements using LINQ to XML
Let us see how to List and Sort all Zip Codes in ascending order
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<string> codes = from code in xelement.Elements("Employee")
                            let zip = (string)code.Element("Address").Element("Zip")
                            orderby zip
                            select zip;
Console.WriteLine("List and Sort all Zip Codes");
 
foreach (string zp in codes)
    Console.WriteLine(zp);
 
VB.NET (Converted Code)
Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim codes As IEnumerable(Of String) = _
      From code In xelement.Elements("Employee") _
      Let zip = CStr(code.Element("Address").Element("Zip")) _
      Order By zip _
      Select zip
Console.WriteLine("List and Sort all Zip Codes")
 
For Each zp As String In codes
      Console.WriteLine(zp)
Next zp
Output:
image_48
 
Section 2: Manipulate XML content and Persist the changes using LINQ To XML
 
9. Create an XML Document with Xml Declaration/Namespace/Comments using LINQ to XML
When you need to create an XML document containing XML declaration, XML Document Type (DTD) and processing instructions, Comments, Namespaces, you should go in for the XDocument class.
C#
XNamespace empNM = "urn:lst-emp:emp";
 
XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "UTF-16", null),
            new XElement(empNM + "Employees",
                new XElement("Employee",
                    new XComment("Only 3 elements for demo purposes"),
                    new XElement("EmpId", "5"),
                    new XElement("Name", "Kimmy"),
                    new XElement("Sex", "Female")
                    )));
 
StringWriter sw = new StringWriter();
xDoc.Save(sw);
Console.WriteLine(sw);
VB.NET (Converted Code)
        Dim empNM As XNamespace = "urn:lst-emp:emp"
 
        Dim xDoc As New XDocument(New XDeclaration("1.0", "UTF-16", Nothing), _
                    New XElement(empNM + "Employees", _
                    New XElement("Employee", _
                    New XComment("Only 3 elements for demo purposes"), _
                    New XElement("EmpId", "5"), _
                    New XElement("Name", "Kimmy"), _
                    New XElement("Sex", "Female"))))
 
        Dim sw As New StringWriter()
        xDoc.Save(sw)
        Console.WriteLine(sw)
image_59
10. Save the XML Document to a XMLWriter or to the disk using LINQ to XML
Use the following code to save the XML to a XMLWriter or to your physical disk
C#
XNamespace empNM = "urn:lst-emp:emp";
 
XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "UTF-16", null),
            new XElement(empNM + "Employees",
                new XElement("Employee",
                    new XComment("Only 3 elements for demo purposes"),
                    new XElement("EmpId", "5"),
                    new XElement("Name", "Kimmy"),
                    new XElement("Sex", "Female")
                    )));
 
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
 
// Save to Disk
xDoc.Save("C:\\Something.xml");
Console.WriteLine("Saved");
VB.NET (Converted Code)
       Dim empNM As XNamespace = "urn:lst-emp:emp"
 
Dim xDoc As New XDocument(New XDeclaration("1.0", "UTF-16", Nothing),_
        New XElement(empNM + "Employees", _
        New XElement("Employee", _
        New XComment("Only 3 elements for demo purposes"), _
       New XElement("EmpId", "5"), _
        New XElement("Name", "Kimmy"), _
        New XElement("Sex", "Female"))))
 
        Dim sw As New StringWriter()
        Dim xWrite As XmlWriter = XmlWriter.Create(sw)
        xDoc.Save(xWrite)
        xWrite.Close()
 
        ' Save to Disk
        xDoc.Save("C:\Something.xml")
        Console.WriteLine("Saved")
 
11. Load an XML Document using XML Reader using LINQ to XML
Use the following code to load the XML Document into an XML Reader
C#
XmlReader xRead = XmlReader.Create(@"..\\..\\Employees.xml");
XElement xEle = XElement.Load(xRead);
Console.WriteLine(xEle);
xRead.Close();
VB.NET (Converted Code)
Dim xRead As XmlReader = XmlReader.Create("..\\..\\Employees.xml")
Dim xEle As XElement = XElement.Load(xRead)
Console.WriteLine(xEle)
xRead.Close()
image_110
 
12. Find Element at a Specific Position using LINQ to XML
Find the 2nd Employee Element
C#
// Using XElement
Console.WriteLine("Using XElement");
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emp1 = xEle.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
 
Console.WriteLine("------------");
 
//// Using XDocument
Console.WriteLine("Using XDocument");
XDocument xDoc = XDocument.Load("..\\..\\Employees.xml");
var emp1 = xDoc.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
VB.NET (Converted Code)
' Using XElement
Console.WriteLine("Using XElement")
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emp1 = xEle.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
 
Console.WriteLine("------------")
 
'// Using XDocument
Console.WriteLine("Using XDocument")
Dim xDoc As XDocument = XDocument.Load("..\..\Employees.xml")
Dim emp1 = xDoc.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
image_211

 

13. List the First 2 Elements using LINQ to XML
List the details of the first 2 Employees
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Take(2);
foreach (var emp in emps)
    Console.WriteLine(emp);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Take(2)
For Each emp In emps
      Console.WriteLine(emp)
Next emp
image_312
14. List the 2nd and 3rd Element using LINQ to XML
List the 2nd and 3rd Employees
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Skip(1).Take(2);
foreach (var emp in emps)
    Console.WriteLine(emp);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Skip(1).Take(2)
For Each emp In emps
      Console.WriteLine(emp)
Next emp
image_413
15. List the Last 2 Elements using LINQ To XML
We have been posting the entire elements as output in our previous examples. Let us say that you want to display only the Employee Name, use this query:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
    Console.WriteLine(emp.Element("EmpId") + "" + emp.Element("Name"));
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2)
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId") + emp.Element("Name"))
Next emp
image_514
To display only the values without the XML tags, use the ‘Value’ property
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
    Console.WriteLine(emp.Element("EmpId").Value + ". " + emp.Element("Name").Value);
 
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2)
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId").Value & ". " & emp.Element("Name").Value)
Next emp
image_115
If you notice, the results are not ordered i.e. the Employee 4 is printed before 3. To order the results, just add call Reverse() again while filtering as shown below:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2).Reverse();
foreach (var emp in emps)
    Console.WriteLine(emp.Element("EmpId").Value + ". " + emp.Element("Name").Value);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
Dim emps = xEle.Descendants("Employee").Reverse().Take(2).Reverse()
For Each emp In emps
      Console.WriteLine(emp.Element("EmpId").Value & ". " & emp.Element("Name").Value)
Next emp
image_216
16. Find the Element Count based on a condition using LINQ to XML
Count the number of Employees living in the state CA
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var stCnt = from address in xelement.Elements("Employee")
            where (string)address.Element("Address").Element("State") == "CA"
            select address;
Console.WriteLine("No of Employees living in CA State are {0}", stCnt.Count());
VB.NET (Converted Code)
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var stCnt = from address in xelement.Elements("Employee")
            where (string)address.Element("Address").Element("State") == "CA"
            select address;
Console.WriteLine("No of Employees living in CA State are {0}", stCnt.Count());
image_317
17. Add a new Element at runtime using LINQ to XML
You can add a new Element to an XML document at runtime by using the Add() method of XElement. The new Element gets added as the last element of the XML document.
C#
 XElement xEle = XElement.Load("..\\..\\Employees.xml");
 xEle.Add(new XElement("Employee",
     new XElement("EmpId", 5),
     new XElement("Name", "George")));
 
 Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
                              New XElement("EmpId", 5), _
                              New XElement("Name", "George")))
 
Console.Write(xEle)
image_418
18. Add a new Element as the First Child using LINQ to XML
In the previous example, by default the new Element gets added to the end of the XML document. If you want to add the Element as the First Child, use the ‘AddFirst()’ method
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.AddFirst(new XElement("Employee",
        new XElement("EmpId", 5),
        new XElement("Name", "George")));
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
   xEle.AddFirst(New XElement("Employee", _
      New XElement("EmpId", 5), _
      New XElement("Name", "George")))
 
Console.Write(xEle)
 
image_518
19. Add an attribute to an Element using LINQ to XML
To add an attribute to an Element, use the following code:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.Add(new XElement("Employee",
        new XElement("EmpId", 5),
        new XElement("Phone", "423-555-4224", new XAttribute("Type", "Home"))));
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
                              New XElement("EmpId", 5), _
                              New XElement("Phone", "423-555-4224", _
                                           New XAttribute("Type", "Home"))))
 
        Console.Write(xEle)
image_119
20. Replace Contents of an Element/Elements using LINQ to XML
Let us say that in the XML file, you want to change the Country from “USA” to “United States of America” for all the Elements. Here’s how to do so:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var countries = xEle.Elements("Employee").Elements("Address").Elements("Country").ToList();
    foreach (XElement cEle in countries)
        cEle.ReplaceNodes("United States Of America");
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim countries = xEle.Elements("Employee").Elements("Address").Elements("Country").ToList()
        For Each cEle As XElement In countries
            cEle.ReplaceNodes("United States Of America")
        Next cEle
 
Console.Write(xEle)
 
image_220
21. Remove an attribute from all the Elements using LINQ to XML
Let us say if you want to remove the Type attribute ( <Phone Type=”Home”>) attribute for all the elements, then here’s how to do it.
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var phone = xEle.Elements("Employee").Elements("Phone").ToList();
    foreach (XElement pEle in phone)
        pEle.RemoveAttributes();
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim phone = xEle.Elements("Employee").Elements("Phone").ToList()
        For Each pEle As XElement In phone
            pEle.RemoveAttributes()
        Next pEle
 
Console.Write(xEle)
image_321
To remove attribute of one Element based on a condition, traverse to that Element and SetAttributeValue("Type", null); You can also use SetAttributeValue(XName,object) to update an attribute value.
 
22. Delete an Element based on a condition using LINQ to XML
If you want to delete an entire element based on a condition, here’s how to do it. We are deleting the entire Address Element
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var addr = xEle.Elements("Employee").ToList();
    foreach (XElement addEle in addr)
        addEle.SetElementValue("Address", null);
 
    Console.Write(xEle);
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
    Dim addr = xEle.Elements("Employee").ToList()
        For Each addEle As XElement In addr
            addEle.SetElementValue("Address", Nothing)
        Next addEle
 
Console.Write(xEle)
 
image_422
SetElementValue() can also be used to Update the content of an Element.
 
23. Remove ‘n’ number of Elements using LINQ to XML
If you have a requirement where you have to remove ‘n’ number of Elements; For E.g. To remove the last 2 Elements, then here’s how to do it
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
    var emps = xEle.Descendants("Employee");
    emps.Reverse().Take(2).Remove();
 
    Console.Write(xEle);
VB.NET (Converted Code)
       Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        Dim emps = xEle.Descendants("Employee")
        emps.Reverse().Take(2).Remove()
 
        Console.Write(xEle)
image_523
24. Save/Persists Changes to the XML using LINQ to XML
All the manipulations we have done so far were in the memory and were not persisted in the XML file. If you have been wondering how to persist changes to the XML, once it is modified, then here’s how to do so. It’s quite simple. You just need to call the Save() method. It’s also worth observing that the structure of the code shown below is similar to the structure of the end result (XML document). That’s one of the benefits of LINQ to XML, that it makes life easier for developers by making it so easy to create and structure XML documents.
C#
    XElement xEle = XElement.Load("..\\..\\Employees.xml");
    xEle.Add(new XElement("Employee",
    new XElement("EmpId", 5),
    new XElement("Name", "George"),
    new XElement("Sex", "Male"),
    new XElement("Phone", "423-555-4224", new XAttribute("Type", "Home")),
    new XElement("Phone", "424-555-0545", new XAttribute("Type", "Work")),
    new XElement("Address",
        new XElement("Street", "Fred Park, East Bay"),
        new XElement("City", "Acampo"),
        new XElement("State", "CA"),
        new XElement("Zip", "95220"),
        new XElement("Country", "USA"))));
 
    xEle.Save("..\\..\\Employees.xml");
    Console.WriteLine(xEle);
 
    Console.ReadLine();           
VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
             New XElement("EmpId", 5), _
             New XElement("Name", "George"), _
             New XElement("Sex", "Male"), _
             New XElement("Phone", "423-555-4224", _
                 New XAttribute("Type", "Home")), _
                 New XElement("Phone", "424-555-0545", _
                   New XAttribute("Type", "Work")), _
                   New XElement("Address", _
                        New XElement("Street", "Fred Park, East Bay"), _
                        New XElement("City", "Acampo"), _
                        New XElement("State", "CA"), _
                        New XElement("Zip", "95220"), _
                        New XElement("Country", "USA"))))
 
        xEle.Save("..\..\Employees.xml")
        Console.WriteLine(xEle)
 
        Console.ReadLine()

Well with that, we conclude this long article of some 'How Do I' operations while using LINQ to XML. Through this article, we have only attempted to scratch the surface of what can be done using LINQ to XML. LINQ to XML is an amazing API and I hope this set of examples has demonstrated that. The entire source of the article in C# and VB.NET can be downloaded over here (Github).

The VB.NET code has been translated using a C# to VB.NET Converting tool.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by SANJAY GUPTA on Thursday, March 31, 2011 7:59 AM
Great Article sir. Hats off to u. Waiting for next superb article.
Comment posted by Meena Damwani on Thursday, August 30, 2012 8:18 AM
Awesome Article... Thanks a lot..
Comment posted by MUBARAK HUSSAIN on Monday, September 3, 2012 2:17 AM
thank u sir,
more help full to me..
Comment posted by Mr. B on Monday, September 24, 2012 10:45 AM
Nicely done, straight to the point with no chewed up grass.
Comment posted by Mr. B on Monday, September 24, 2012 11:30 AM
Nicely done, straight to the point with no chewed up grass.
Comment posted by mat on Tuesday, October 2, 2012 3:13 PM
In the beginning is a nice application <a href="http://www.matbaashow.com">matbaa</a>
Comment posted by Purushottam on Friday, November 16, 2012 5:31 AM
Awesome!!! Whole LINQ to XML in one shot.. GR8 articel...
Comment posted by Bhumi on Saturday, November 17, 2012 1:30 AM
Very nice example help a lot to me
Comment posted by Sudha Vijayakumar on Monday, November 26, 2012 8:20 AM
Wonderful article !
Comment posted by The Biggest Bunny Ever on Saturday, December 1, 2012 2:55 PM
Very, very nice tutorial.  Thank you very much.
Comment posted by BW on Monday, December 3, 2012 12:33 PM
Just the article I needed to get me up and running quickly. Thanks. BW
Comment posted by Monir on Friday, December 7, 2012 10:31 AM
Awesome.....
Comment posted by Kiri on Saturday, December 15, 2012 9:53 PM
maximum...
Comment posted by Eaglesd on Monday, December 17, 2012 9:40 AM
One of the best explanations on LINQ I have found. Thanks for sharing your knowledge.
Comment posted by Reza Khan on Thursday, December 27, 2012 10:00 AM
Hi , your article is just superb and covers a lot of ground , well done and thanks,
Reza
Comment posted by srinivas M on Saturday, January 12, 2013 6:11 AM
Very nice article. Helps a lot for beginners. Wonderful....
Comment posted by shawn kountz on Friday, January 25, 2013 10:36 PM
Best article ever on LINQ to XML,Thank you for very very very clear examples!!
Comment posted by Abdur Rahman on Monday, February 4, 2013 5:27 AM
Thnaks for needful article....
Comment posted by Bishoy Wasfy on Monday, February 11, 2013 6:38 AM
Fantastic article.
Comment posted by Upendra on Tuesday, February 12, 2013 8:06 PM
Can you please share some samples of querying an xml to fetch an element with a given value of an attribute ?
say I have xml file of students containing element "student" with attribute "rollno" . The element "student" is contained within top level element "students". I need to query for student element for rollno=some value.
Comment posted by Joop Hooymans on Thursday, February 14, 2013 12:24 PM
Thank you for the fantastic clear tutorial!!

Nr. 16 did not work properly.(a mistake maybe? My correction dis his work well:

       xelement = xelement.Load("D:\Employees.xml")
        Dim emp6 = From address In xelement.Elements("Employee") Where address.Element("Address").Element("City") = "Montara" Select address
        Console.WriteLine("Employees living in Montara City are {0}", emp6.Count())
Comment posted by Brian on Sunday, February 17, 2013 8:57 PM
Excellent article. You covered every scenario I can think of. I knew how to query the data, my questions were related to adding/removing and persisting. All answered, thank you!
Comment posted by Suprotim Agarwal on Wednesday, February 20, 2013 12:33 AM
Joop: Seems to be working fine. What error do you get?

Brian: Glad it helped :)
Comment posted by Said WAHID on Saturday, March 2, 2013 5:51 AM
thank you
Comment posted by aman goel on Thursday, March 21, 2013 4:54 PM
This will not work for windows phone. I can not able to add new record in my existing xml file
Comment posted by Venki on Tuesday, April 2, 2013 11:46 PM
You are simply superb (LINQ) man!!!
Comment posted by Pooja Gaur on Thursday, April 4, 2013 4:49 AM
this is really good. I have learnt a lot from it. From beginner to experts,everybody can get profit from this.
Comment posted by Dmitrij on Friday, April 19, 2013 1:37 AM
thank. your examples very illustrative
Comment posted by Gaurang Naik on Monday, May 6, 2013 1:20 PM
Absolutely fantastic. Contributions like such keeps the programming going.
Thank you very much sir.
Comment posted by Jon on Monday, May 13, 2013 11:08 AM
Excellent article, very good to the point explanation without the usual cumbersome chatter! Thanks a lot!
Comment posted by Srividhya on Saturday, May 25, 2013 5:50 AM
Very clear! A great and generous contribution to the developer community!
Comment posted by Mallika on Monday, June 17, 2013 9:06 PM
Fantastic. Saves my time
Comment posted by Roncesvalles on Sunday, June 23, 2013 5:30 PM
Many thanks, your article is awesome!
Comment posted by Avinash on Tuesday, July 2, 2013 4:46 AM
Awesome, really wonderful article.. Thank u so much for publishing such a nice article..
Comment posted by Arthur on Friday, July 19, 2013 12:31 PM
Excellent article, very helpful!
Comment posted by Dheeraj Kumar Baweja on Monday, July 29, 2013 1:37 PM
Thank you for sharing such a good n useful article, its really very helpful!! Thanx a lot
Comment posted by all on Wednesday, July 31, 2013 8:31 AM
Good article, thank you
Comment posted by Konstantin on Thursday, August 1, 2013 10:08 AM
It is a pity that I did not find it sooner. Advise your article to all newcomers. Many thanks for your work.
Comment posted by Michael on Wednesday, August 7, 2013 7:57 PM
One word - Excellent!
Comment posted by Sravani on Friday, August 23, 2013 11:46 AM
Thanks a lot. can u please use with a form like dropdown list and a textbox in which dropdown will get sll heasder and textbox will display the values
Comment posted by karolina on Friday, August 30, 2013 4:16 PM
o! It is amazing tutorial :) Thanks for it i learned very much .
Comment posted by Gaurav Agarwal on Wednesday, September 25, 2013 5:18 AM
Fantastic
Comment posted by Solid on Friday, October 4, 2013 3:42 AM
none of these work because you forgot about xnamespace.

I don't know how you got it to work without it...
Comment posted by blovett on Tuesday, October 15, 2013 2:59 PM
First, awesome stuff.  Thank you so much for doing it.  Second, I will likely keep coming back here from time to time as it is a great repository and a good place to refresh my memory when I am looking to do stuff.  One thing missing that can be difficult to find (I am looking for it now), is how to take a node and convert its children to attributes, and the reverse.  If anyone needs to know, converting elements to attributes can GREATLY reduce the size of an XML document.

Thanks again!
Comment posted by karl on Wednesday, October 30, 2013 1:58 PM
Hello
This doesn't work correct
Art.5
var homePhone = from phoneno in xelement.Elements("Employee")
                where (string)phoneno.Element("Phone").Attribute("Type") == "Home"
                select phoneno;

it will filter only the phones which are on the first position.
if you change the Home phone to the second position it will not be shown
Comment posted by rajesh on Wednesday, November 20, 2013 11:13 PM
superb
Comment posted by Rob on Tuesday, November 26, 2013 9:44 AM
This saved me days of work. Great job! Many thanks.
Comment posted by Rick Eis on Monday, December 9, 2013 12:04 PM
Nice set of examples
Comment posted by Girdar on Friday, December 13, 2013 3:46 AM
Thanks.. your examples are dam good
Comment posted by Shivaraj on Thursday, December 19, 2013 1:51 AM
Very nice article
Comment posted by Anonymous on Friday, December 20, 2013 12:09 PM
Thanks Sir, it was very helpful.
Comment posted by Jakir Chowdhury on Sunday, December 29, 2013 11:12 PM
Hello:-
Thank you for the great posts.  I am trying to use linq to return multiple fields and at the same time apply sorting.  Can you please post an article describing how to do this?

Thank you very much in advance.

Comment posted by James Watson on Monday, April 21, 2014 6:37 AM
I have XML that looks like this:
<?xml version='1.0' encoding='utf-8'?><ContentStack ID='13' Type='11'><ContentElement1 ID='11' Type='IMAGE'><Key AttributeName='Name' AttributeValue='tsss'></Key><Key AttributeName='SRC' AttributeValue='sdfadsfa'></Key><Key AttributeName='ALT' AttributeValue='asdff'></Key><Key AttributeName='WIDTH' AttributeValue='4334'></Key><Key AttributeName='Class' AttributeValue='asdf'></Key></ContentElement1></ContentStack>

I want to be able to pull out the attributeValue and assign it to a variable for each Key not having any luck tried xDoc.Descendants("Key.AttributeValue").Skip(0).Take(1).ToString
Comment posted by Hamdi KARA on Thursday, May 8, 2014 2:38 AM
Hi :-)
Thank you very much.
Çok teşekkürler çok faydalı bir yazı.
Comment posted by Aron on Thursday, May 8, 2014 6:39 AM
Thank you this was priceless for me
Comment posted by mimarfe on Saturday, May 10, 2014 2:06 PM
muy agradecido por este tutorial es el mejor que he visto y me ha servido de gran ayuda
Comment posted by Fernando Novoa on Monday, May 12, 2014 11:11 PM
Just what I needed!!!
Comment posted by Ajay Singh on Thursday, May 22, 2014 4:49 AM
Very-very nice article on LINQ to XML.
Comment posted by Renato Pisani on Thursday, July 3, 2014 5:28 AM
Hi.

I have the following file XML:
<Top>
<Top1>
<Top1.1>Data1</Top1.1>
...
</Top1>
</Top>

I need to insert one or more elements like the following:

<Top2>
<Top2.1>Data1</Top2.1>
<Top2.2>Data2</Top2.2>
...
</Top2>

at Runtime after </Top1> using Linq2Xml e VB.

In addition, to complete, I should insert other elements similar to <Top2> after <Top2> if exists otherwise after <Top1>.

Thanks.
Comment posted by Bastin on Tuesday, July 8, 2014 2:02 AM
Nice Article . Thank U........
Comment posted by Dan on Wednesday, July 9, 2014 7:38 PM
# 17. Add a new Element at runtime using LINQ to XML

VB.NET (Converted Code)
Dim xEle As XElement = XElement.Load("..\..\Employees.xml")
        xEle.Add(New XElement("Employee", _
                              New XElement("EmpId", 5), _
                              New XElement("Name", "George")))

Can you expand on this and show how to add finish adding all the nodes for the employee. Per your example the address node.


<Employee>
    <EmpId>1</EmpId>
    <Name>Sam</Name>  
    <Sex>Male</Sex>
    <Phone Type="Home">423-555-0124</Phone>
    <Phone Type="Work">424-555-0545</Phone>
   <Address>
      <Street>7A Cox Street</Street>
      <City>Acampo</City>
      <State>CA</State>
      <Zip>95220</Zip>
      <Country>USA</Country>
    </Address>
</Employee>

Please respond to my email....Thanks
Comment posted by eduard on Wednesday, July 16, 2014 9:10 AM
Well, I share the problem of:
"Comment posted by karl on Wednesday, October 30, 2013 1:58 PM"

could it be that it comes with .NET 4.5?
or... how do I solve this?

Thank you for your kind consideration,

greetings

ed
Comment posted by ed on Wednesday, July 16, 2014 10:41 AM
oh wow, I forgot to actually give a big THANK YOU first, because everything else is a wonderfully explained tutorial... it really is!

it's just that: I need to work with Attributes, and can't figure out how to
Comment posted by ed on Thursday, July 17, 2014 2:32 AM
oh wow, I forgot to actually give a big THANK YOU first, because everything else is a wonderfully explained tutorial... it really is!

it's just that: I need to work with Attributes, and can't figure out how to
Comment posted by semaro on Friday, September 26, 2014 9:17 AM
Great Tutorial and thank you.
However, how to read all values with complex XML like (one level add)

<?xml version="1.0" encoding="UTF-8"?>
<TITRE>  
<GROUPE>  <---------- adding this level !!  
  <DATA>
     <NOM>NOM_1</NOM>
     <ADRESSE>
        <RUE>RUE_1</RUE>
        <CP>CP_1 </CP>
        <VILLE>VILLE_1</VILLE>
     </ADRESSE>
     <CONTACT>
        <NUM>CODE_1</NUM>
        <DATE>DATE_1</DATE>  
     </CONTACT>
     <CONTACT>
        <NUM>CODE_2</NUM>
        <DATE>DATE_2</DATE>  
     </CONTACT>
  </DATA>
  <DATA>
     <NOM>NOM_2</NOM>
     <ADRESSE>
         <RUE>RUE_2</RUE>
         <CP>CP_2 </CP>
         <VILLE>VILLE_2</VILLE>
    </ADRESSE>  
    <CONTACT>
         <NUM>CODE_3</NUM>
         <DATE>DATE_3</DATE>  
    </CONTACT>
    <CONTACT>
         <NUM>CODE_4</NUM>
         <DATE>DATE_4</DATE>  
    </CONTACT>
   </DATA>
</GROUPE>
</TITRE>

Comment posted by megha on Wednesday, December 17, 2014 5:31 AM
I have two xmls merged and added in one Xdocument. two xml contents are different by one field only. How to access these objects in loop?
Comment posted by Mike Baradaran on Friday, April 24, 2015 3:40 AM
Awsome examples!
Thank you so much for posting this article.