0

我有需要使用 XDocument 处理的 xml 文档

<elem c="98500000">
    <elem c="98510000">
      <elem c="98511000"/>
      <elem c="98512000"/>
      <elem c="98513000">
        <elem c="98513100"/>
        <elem c="98513200"/>
        <elem c="98513300"/>
        <elem c="98513310"/>
      </elem>
      <elem c="98514000"/>
    </elem>
  </elem>

我尝试通过选定的节点属性获取最小子树,例如 98512000, 98513300, 98514000 :

<elem c="98500000">
    <elem c="98510000">
      <elem c="98512000"/>
      <elem c="98513000">
        <elem c="98513300"/>
      </elem>
      <elem c="98514000"/>
    </elem>
  </elem>
4

1 回答 1

1

给定所需c值的列表,您可以删除c属性值不在列表中且没有后代元素c在列表中具有属性值的元素:

var doc = XDocument.Parse("your XML document string here");
var list = new List<string>(){"98512000", "98513300", "98514000"};
doc.Descendants()
    // all `c` value doesn't match current element's `c` attribute value
   .Where(o => list.All(c => (string)o.Attribute("c") != c) 
                    && 
    // and all descendant elements doesn't have matching `c` attribute value
               o.Descendants().All(d => !list.Any(c => (string)d.Attribute("c") == c)))
   .Remove();
Console.WriteLine(doc.ToString());

dotnetfiddle demo

输出 :

<elem c="98500000">
  <elem c="98510000">
    <elem c="98512000" />
    <elem c="98513000">
      <elem c="98513300" />
    </elem>
    <elem c="98514000" />
  </elem>
</elem>
于 2017-03-17T01:51:16.350 回答