Modifying existing xml attributes value using LINQ

In the previous post i showed a way to read attributes values of XML node from XML file. In today's example i will be sharing a way in which the existing attributes value can be modified with the use of LINQ in C#. 

Herein the sample customers.xml file used for the current example

Customers.xml
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <customer name="Steve John" Id="CUST0001" location="New York" 
  country="United States" DOB="12/23/1960Phone="+12126661111"/>
  <customer name="Sagar Mehta" Id="CUST0106" location="Bangalore" 
   country="India" DOB="07/23/1978" Phone="+918088881001" />
  <customer name="Rahul Raj" Id="CUST0190" location="Delhi" 
   country="India" DOB="01/31/1980" Phone="+911166661111" />
  <customer name="John Roderix" Id="CUST0301" location="Sydney" 
   country="Australia" DOB="02/13/1956" Phone="+61(0)280623999"/>
</Customers>

Loading the customers xml into the XDocument object:

XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory+ "/Customers.xml");

Retrieving all the customers details from attributes and modifying the city and emailid details of Customer "Aryan Mehta".

//retreiving all the elements from the customers.xml

IEnumerable<XElement> rows = 
                         from row in xDoc.Descendants("Customer")
                         select row;


//retreiving the first element from the collection to modify city and email id
XElement xele = (XElement)rows.ElementAt(0);

//setting the city attribute value
xele.Attribute("city").SetValue("Delhi");

//setting the emailid attribute value
xele.Attribute("emailid").SetValue("aryanmehta@microsoft.com");

//setting the row to null
rows = null;

//retrieving the details of customer = "Aryan Mehta"
rows = from row in xDoc.Descendants("Customer")
       where (string)row.Attribute("name") == "Aryan Mehta"
       select row;

//retrieving all the attributes from the element
IEnumerable<XAttribute> attList = 
               from att in rows.DescendantsAndSelf().Attributes()
               select att;

foreach (XAttribute xatt in attList)
{
     Console.WriteLine(xatt);
}


As you can see in the output window, the customer details has been modified.

I have used Console.Write for writing the output to demonstrate the output retrieved. You can use any way the data is required to be displayed or stored in a collection.


Happy Coding.........

Comments