Linq to XML 联接并添加数据?
给定这样的 XML:
<Root>
<Element>
<Id>1</Id>
</Element>
<Element>
<Id>2</Id>
</Element>
<Element>
<Id>3</Id>
</Element>
</Root>
以及包含此数据的 IEnumerable:
[0] = { Id = 1, Data = 429 }
[1] = { Id = 2, Data = 271 }
[2] = { Id = 3, Data = 328 }
是否有一种优雅的方法使用 LINQ to XML 将 IEnumerable 数据与基于公共 Id
的 XML 连接起来,而无需单独查询每个元素来链接数据与?
所以结果看起来像这样:
<Root>
<Element>
<Id>1</Id>
<Data>429</Data>
</Element>
<Element>
<Id>2</Id>
<Data>271</Data>
</Element>
<Element>
<Id>3</Id>
<Data>328</Data>
</Element>
</Root>
我唯一能想到的就是这样的东西,但我希望有一个更干净的方法:
foreach(var d in MyIEnumerable)
{
XElement element = (from x in MyXDoc.Elements("Element")
where x.Element("Id").Value == d.Id
select x).Single();
element.Add(new XElement("Data", d.Data));
}
Given XML like this:
<Root>
<Element>
<Id>1</Id>
</Element>
<Element>
<Id>2</Id>
</Element>
<Element>
<Id>3</Id>
</Element>
</Root>
And an IEnumerable with this data:
[0] = { Id = 1, Data = 429 }
[1] = { Id = 2, Data = 271 }
[2] = { Id = 3, Data = 328 }
Is there an elegant way using LINQ to XML to join the IEnumerable data with the XML based on the common Id
without individually querying for each element to link the data with?
So the result would look like this:
<Root>
<Element>
<Id>1</Id>
<Data>429</Data>
</Element>
<Element>
<Id>2</Id>
<Data>271</Data>
</Element>
<Element>
<Id>3</Id>
<Data>328</Data>
</Element>
</Root>
The only thing I can come up with is something like this, but I was hoping there was a cleaner method:
foreach(var d in MyIEnumerable)
{
XElement element = (from x in MyXDoc.Elements("Element")
where x.Element("Id").Value == d.Id
select x).Single();
element.Add(new XElement("Data", d.Data));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是使用
Tuple
。 (Element
是包含 ID 和数据的类。)如果您没有元组,那么您可以创建一个匿名类。
One way is to use a
Tuple<Element, XElement>
. (TheElement
is the class that has ID and Data in it.)If you don't have tuples then you can create an anonymous class instead.
您也许可以执行以下操作:
其中
Apply
扩展方法定义为:You might be able to do something like:
Where the
Apply
extension method is defined as: