Linq to XML - Select 多个元素

Linq to XML - Select multiple elements

我有一个 xml 文件,其中包含一系列汽车。如果汽车是绿色的,我想删除一个元素 AB

<?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>

我愿意:

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();

这是行得通的,但是如何在一行中完成呢?如何 select Select 中的两个元素?

谢谢

这是一种可能的方法,找到值等于 'Green' 的 Color 元素,使用 ElementsAfterSelf(), flatten them using SelectMany() 获取以下所有同级元素,最后删除它们:

XDocument.Root
         .Descendants("Car")
         .Elements("Color")
         .Where(c => c.Value == "Green")
         .SelectMany(c => c.ElementsAfterSelf())
         .Remove();

更新:

如果目标元素严格需要通过名称来标识,例如不一定是 <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();

如果目标元素名称列表可能增长到超过 2 个("A" 和 "B"),我建议使用数组和 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();