将XElement加载到DataTable中

3
我有以下XML文件,包含关于公司分支机构的大量信息... (这只是一个例子)。
我真正需要的是只加载Branch1中的数据到一个数据表中(该数据表具有与我的XML文件相同的结构,因此数据表没有问题)。
我使用C#,我想用LINQ来实现这个,但我对LINQ一无所知... 我的问题是: 我如何将从XML读取的条目作为数据表行,以便我可以将其复制到我的数据表中?
现在我有:
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);

任何的帮助都非常感激。。
<?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>

你可能将“LINQ”和“LINQ to SQL”混淆了。你应该避免使用LINQ to SQL,而应该考虑使用Entity Framework。 - John Saunders
嗨John... 这与SQL无关,我只是将我的XML内容加载到一个数据表中...很抱歉,可能我没有完全理解你的意思! 我正在使用C#进行编程...谢谢你的回答。 - lebhero
1个回答

6

尝试

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

我遇到了一个“路径中有非法字符”的异常。 - lebhero
(new XElement("branches", elList).ToString()) 将整个 XML 节点放入另一个 <branch></branch> 标签中...这意味着现在我得到了以下结果: <branch> <branch name="branch1"> <address>Street 1, 1234, NY</address> <tel>0123456789</tel> <director>James</director> </branch> </branch> - lebhero
嗨...在我选择想要的节点之后,它应该像这样:<branch name="branch1"> <address>Street 1, 1234, NY</address> <tel>0123456789</tel> <director>James</director> </branch>没有额外的开头和结尾的<branch>标签... - lebhero
@lebhero 添加了 StringReader.. 看看是否有帮助。 - Bala R
@lebhero 我没有带有关联架构的数据表,所以无法测试它。但是代码的其余部分过滤了分支并正确产生了 XML。 - Bala R
我的错误,它现在可以工作了...我只是打错了“分支”..谢谢。 - lebhero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接