带有XDocument的xml上的最小子树

时间:2017-03-16 22:39:47

标签: c# xml linq-to-xml spanning-tree

我有需要使用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>

1 个答案:

答案 0 :(得分: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>