[英]Linq to XML - Select multiple elements
I have one xml file with a collection of cars. 我有一个带有汽车集合的xml文件。 I want to remove a element A
and B
if the car is green : 如果汽车是绿色的,我想删除元素A
和B
:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Cars>
<Car>
<Color>Green</Color>
<A>Value</A>
<B>Value</B>
</Car>
<Car>
<Color>Blue</Color>
<A>Value</A>
<B>Value</B>
</Car>
<Car>
<Color>Yellow</Color>
<A>Value</A>
<B>Value</B>
</Car>
</Cars>
I do : 我做 :
XDocument.Root.Descendants("Car").Where(x => x.Element("Color").Value == "Green"). Select(x => x.Element("A")).Remove();
XDocument.Root.Descendants("Car").Where(x => x.Element("Color").Value == "Green"). Select(x => x.Element("B")).Remove();
It's work but how to do this in one line ? 它正在工作,但是如何在一排中做到这一点? How to select two elements in Select
? 如何在Select
选择两个元素?
Thank's 谢谢
This is one possible way, find Color
element where value equals 'Green', grab all the following sibling elements using ElementsAfterSelf()
, flatten them using SelectMany()
, and finally remove them : 这是一种可能的方法,找到Color
元素,其值等于'Green',使用ElementsAfterSelf()
捕获以下所有同级元素,使用SelectMany()
展平它们,最后删除它们:
XDocument.Root
.Descendants("Car")
.Elements("Color")
.Where(c => c.Value == "Green")
.SelectMany(c => c.ElementsAfterSelf())
.Remove();
UPDATE : 更新:
If the target elements strictly need to be identified by name eg not necessarily all elements after <Color>
, you can use Where()
method as follow : 如果严格需要通过名称来标识目标元素,例如不一定是<Color>
之后的所有元素,则可以使用Where()
方法,如下所示:
XDocument.Root
.Descendants("Car")
.Where(c => (string)c.Element("Color") == "Green")
.SelectMany(c => c.Elements()
.Where(e => e.Name.LocalName == "A" ||
e.Name.LocalName == "B"))
.Remove();
If list of target element names may grow to more than 2 ("A" and "B"), I'd suggest to use array and Contains()
for filtering : 如果目标元素名称列表可能增长到2个以上(“ A”和“ B”),则建议使用array和Contains()
进行过滤:
var targetElementNames = new[]{ "A", "B", "C" };
XDocument.Root
.Descendants("Car")
.Where(c => (string)c.Element("Color") == "Green")
.SelectMany(c => c.Elements()
.Where(e => targetElementNames.Contains(e.Name.LocalName))
.Remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.