How to join xml and datatable via linq

374 Views Asked by At

I have a datatable which is holding two columns as 'Name' and 'Value'.

I have xml also which looks like below so I need to join datatable column with XML attribute then select XML Value if attribute value are present in datatable column. I have tried many possible ways but none of them helped . Please help me how to achieve this with help of linq!

Below is XML code

<Serverlist>
    <server name='Eric' value='9' />
    <server name='Donot' value='92' />
</Serverlist>

Below is code snippet which I have used

XElement xelement = XElement.Load("path");

var data = from dtt in dt.AsEnumerable()
           join xele in xelement.Descendants("server")
           on (string)dtt.Field<string>("Name") equals (string)xele.Attribute("name")
           select new { name =(String) xele.Attribute("name"), value=(string) xele.Attribute("value")};

foreach(var v in data) 
{
    Console.WriteLine(v);
}
1

There are 1 best solutions below

0
Murray Foxcroft On

I think you are trying to merge as opposed to join?

Convert them both to Dictionaries (the database list and the xml document). Then merge the two dictionaries together. Good examples are in this thread. for example:

dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
Simple and easy. According to this blog post it's even faster than most loops.