Tuesday, January 24, 2012

Reading Xml Elements contained within a XML using LINQ

In today's post i will read an XML file whose root node contains only XML elements. And this task will be achieved with the help of LINQ in C#.

Following Customer.xml file will be used for this sample demonstration:-

Customer.xml
<?xml version="1.0" encoding="utf-8" ?>
<Customer>   
    <Name>Steve Smith</Name>
    <CompanyName>Star Infotech Ltd</CompanyName>
    <JobTitle>Project Manager</JobTitle>
    <Address>133, 13th Floor, 2nd Street</Address>
    <City>New York</City>
    <Country>United States</Country>
    <Phone>+12126661111</Phone>
    <Fax></Fax>
    <EmailId>Steve.Smith@Sinfotech.com</EmailId>
</Customer>

 //Loading the customers xml into the XDocument object:
XDocument xDoc = 
            XDocument.Load(AppDomain.CurrentDomain.BaseDirectory+ "/Customers.xml");

//retreiving all the elements which are part of root node Customer
IEnumerable<XElement> custDetails = 
                                                    from row in xDoc.Descendants("Customer").Elements()
                                                    select row;

 foreach (XElement xEle in custDetails)
 {
     //Displaying the Customer details one Xml Element at a time
     Console.WriteLine(xEle);
 }


Output:-
---------

You can see the details of the customer in the console output window.

Its really amazing how easy and helpful LINQ is to work with XML.


Happy Coding............

Wednesday, January 18, 2012

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);
}

Output:-

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.........

Thursday, January 12, 2012

Reading XML nodes Attributes values using LINQ in C#

Recently i came across a requirement where i was supposed to read a XML file. But this time the requirement was to read the values from XML file which were declared as Attributes in XML node as opposed to XML node child elements.

In today's example i will be sharing the solution with the use of LINQ in C# for achieving the same results with a sample xml.

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/1960" Phone="+1 212 666 1111" />
  <customer name="Sagar Mehta" Id="CUST0106" location="Bangalore" country="India" DOB="07/23/1978" Phone="+91 80 8888 1001" />
  <customer name="Rahul Raj" Id="CUST0190" location="Delhi" country="India" DOB="01/31/1980" Phone="+91 11 6666 1111" />
  <customer name="John Roderix" Id="CUST0301" location="Sydney" country="Australia" DOB="02/13/1956" Phone="+61 (0)2 8062 3999" />
</Customers>

Loading the customers xml into the XDocument object:

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


Requirement 1: Retrieving all the customers details in Attributes Name,value format whose details match the city="Bangalore"

IEnumerable<XElement> rows = from row in xDoc.Descendants("customer")
                where (string)row.Attribute("country") == "India" 
                select row;

//looping through the XElement details one by one
foreach (XElement ele in rows)
{
 //for the current xElement retrieving all the Attributes details
 IEnumerable<XAttribute> attList = 
                from att in ele.DescendantsAndSelf().Attributes()
                select att;

 //Looping through attributes list and displaying it on the screen
   foreach (XAttribute att in attList)
   {
         Console.WriteLine(att);
   }

   //Just to show a separator between two customer details
   Console.WriteLine("---First customer details ends here ----");
}

Output:-



Requirement 2: Retrieving all the customers details in Attributes Name,value format whose details match the city="Bangalore" and country ="India"

IEnumerable<XElement> rows = 
              from row in xDoc.Descendants("customer")
              where (string)row.Attribute("country") == "India"
                    (string)row.Attribute("city") == "Bangalore"
              select row;
//looping through the XElement details one by one
foreach (XElement ele in rows)
{
 //for the current XElement retrieving all the Attributes details
 IEnumerable<XAttribute> attList = 
              from att in ele.DescendantsAndSelf().Attributes()
              select att;

//Looping through attributes list and displaying it on the screen
 foreach (XAttribute att in attList)
 {
    Console.WriteLine(att);
 }
}

Output:



Requirement 3: Retrieving all the customers details as Attribute value whose details match the city="Sydney" and 
country ="Australia"

IEnumerable<XElement> rows = 
            from row in xDoc.Descendants("customer")
            where (string)row.Attribute("country") == "Australia" 
                & (string)row.Attribute("city") == "Sydney"
            select row;

//looping through the XElement details one by one
foreach (XElement ele in rows)
{
 //for the current XElement retrieving all the Attributes details
 IEnumerable<XAttribute> attList = 
               from att in ele.DescendantsAndSelf().Attributes()
               select att;

//Looping through attributes list and displaying it on the screen
 foreach (XAttribute att in attList)
 {
    //retrieving the attribute value
    Console.WriteLine(att.Value);
 }
}

Output:


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.........