Microsoft > CSharp >> Code Snippets Views : 5514
Rate This Article :

Working with XML using LINQ


This article explains,

  •  How to read the XML using LINQ
  • How to update the XML element values using LINQ


Below namespace needs to added in order to work using LINQ

using System.IO;

using System.Linq;

using System.Xml;

using System.Xml.Linq;


Sample XML String:

private const string XmlValue = @"<RootNode>



















                  <Value />







Read and Update the XML string:

Here I have used StringReader and XML Reader to read the XML string.


In this case, XmlReader is used to read the XML string. In case of XML file, XDocument will work with XMLReader.

XMLReader has below overload methods to read the XML String:



XDocument has below overload methods to load the XML values:


Below code explains how to work with XmlReader and XDocument using LINQ

            // Reading the XML string using XmlReader to pass to XDocument.

            using (var reader = XmlReader.Create(new StringReader(XmlValue)))


                // Loads the XDocument

                var xdoc = XDocument.Load(reader);


                // Using LINQ Query to find the items in the XML.

                var attributes = from level1 in xdoc.Descendants("Item")

                                 select new


                                     Key = level1.Element("Key").Value,

                                     Value = level1.Element("Value").Value



                // Finding the keys/search values

                var keyAttribute = attributes.FirstOrDefault(p => p.Key == "ItemKey3");


                if (keyAttribute != null)


                    // Updating the element value directly on the XML string.

                    xdoc.Descendants("Item").Where(p => p.Element("Key").Value == "ItemKey3").Single().SetElementValue("Value", "1000");



                var updatedString = xdoc.ToString(); // This has the updated XML string.


                // Save the document in the desired path.



About Author
Raj Kumar
Total Posts 55
Developer in .Net!
Comment this article
Email Address* (Will not be shown on this website.)
Enter Image Text*
View All Comments
Nice and simple explanation.
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.