Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

c# - load xelement into a datatable

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try

branchesDataTable.ReadXml(new StringReader(new XElement("branches", elList).ToString()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...