3

i have the following xml file, that contains a lot of Information about branches of a company .. (this is only an example)..

what i really need, is to load only the data from Branch1 in a datatable(that has the same structure as my xml file, so no problem with the datatable at all) ..

iam using c# and i would like to do this is linq, but i have no idea about linq... my question is: how would i read the entry from xml as a datatable row, so i can copy it to my datatable ?

i now have:

XElement main = XElement.Load("branches.xml");
IEnumerable<XElement> elList =
from el in main.Descendants("branch").Where(ex=>ex.Attribute("name").Value=="Branch1")
select el;
//this will return me the element where name =Branch1
//now, how would i only load this entry into my datatable ??
//this won`t work
branchesDataTable.ReadXml(XElement el in elList);

any help is really appreciated ..

<?xml version="1.0" encoding="utf-8"?>
<branches>
<branch name="Branch1">
    <address>Street 1, 1234, NY</address>
    <tel>0123456789</tel>
    <director>James</director>
</branch>   
<branch name="Branch2">
    <address>Street 2, 4567, NY</address>
    <tel>9876543210</tel>
    <director>Will</director>
</branch>
</branches>
John Saunders
  • 160,644
  • 26
  • 247
  • 397
lebhero
  • 1,391
  • 5
  • 18
  • 35
  • You may be confusing "LINQ" with "LINQ to SQL". You should probably not use LINQ to SQL, but should instead look at Entity Framework. – John Saunders Sep 29 '11 at 19:46
  • hi john... it has nothing to do with sql, iam just loading my xml contents into a datatable...sorry iam may didnt understand what you mean exactly !?iam programming in C#...thx for your answer – lebhero Sep 29 '11 at 19:48

1 Answers1

6

try

branchesDataTable.ReadXml(new StringReader(new XElement("branches", elList).ToString()));
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • iam getting an "Illegal characters in path" Exception – lebhero Sep 29 '11 at 20:07
  • the (new XElement("branches", elList).ToString()) is putting the whole xml node in another tag...this means iam getting the following now :
    Street 1, 1234, NY
    0123456789 James
    – lebhero Sep 29 '11 at 20:11
  • hi ...it should be like this after i choose which node i want :
    Street 1, 1234, NY
    0123456789 James
    without the extra opening and ending tags ...
    – lebhero Sep 29 '11 at 20:16
  • @lebhero added StringReader.. see if that helps. – Bala R Sep 29 '11 at 20:16
  • @lebhero I don't have the datatable with associated schema so I cannot test it. but the rest of the code filters the branches and correctly produces xml. – Bala R Sep 29 '11 at 20:21
  • my mistake, it works ... i just mistyped the "branches" ..thank you – lebhero Sep 29 '11 at 21:12