Naveen's Weblog

Bridge to future

Join XML using LINQ

Posted by codingsense on September 23, 2008


Hi All,

Today i have come with joining of 2 XML files using a relation using linq.

I will take a scenario where the clients are recognized by clientID , the basic information of each client (ID, Name and address) is stored at one place and the salary details (ID, Salary) will be stored at another place. Lets see what can be done If we need to join both these files into one.

 

Problem View::

Download Sample – 29kb

Create ClientInfo XML::

Here we shall create an XML of client data. Consider ID to be Unique Number (primary key). For each client we will have details like ID, name and address.

XElement ClientInfo = new XElement("Clients",
new XElement("Client",
new XElement("ID", "1"),
new XElement("Name", "Client1"),
new XElement("Address", "Mahalaxmi")
),
new XElement("Client",
new XElement("ID", "2"),
new XElement("Name", "Client2"),
new XElement("Address", "J.C.Road")
),
new XElement("Client",
new XElement("ID", "3"),
new XElement("Name", "Client3"),
new XElement("Address", "M.G.Road")
)
);

 

Output::

Create Salary XML::

Now we shall create an XML that will store the salary of each clients with their respective client ID.

XElement Salary = new XElement("Salaries",
new XElement("Salary",
new XElement("ID", "1"),
new XElement("Amount", "20000")
),
new XElement("Salary",
new XElement("ID", "3"),
new XElement("Amount", "30000")
),
new XElement("Salary",
new XElement("ID", "3"),
new XElement("Amount", "40000")
)
);

Output::


Join Both XML::

Lets try to join both the XML using the client ID and make them into one XML that will consist some elements of client info and some of salary .

XElement Join = new XElement("Clients",
from client in ClientInfo.Elements()
from sal in Salary.Elements()
where client.Element("ID").Value == sal.Element("ID").Value
select new XElement("Client", client.Descendants(), sal.Elements("Amount"))
);

Output:

Hope all of you got how to join two XML using an element as relation using LINQ.

Keep Exploring 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: