如何从父xml文件中提取特定节点?

时间:2016-06-02 09:59:57

标签: c# xml linq

我有一个xml文件,我想从中提取id属性为“Needed”的节点:

<root>
<level1 id="NotNeeded">
</level1>
<level1 id="Needed">
    <level2 id="Needed">
        <level3 id="Needed">I need this one</level3>
        <level3 id="NotNeeded1">I don't need this one</level3>
    </level2>
    <level2 id="notNeeded">
        <level3 id="notNeeded">I don't need this one</level3>
    </level2>
</level1>
</root>

(深度是任意的) 我需要将其转换为以下形式:

<root>
<level1 id="Needed">
    <level2 id="Needed">
        <level3 id="Needed">I need this one</level3>
    </level2>
</level1>
</root>

我正在尝试做什么(使用伪代码,我希望它很清楚):

myextraction=[element with id "Needed"]
while [myextraction has parent]
{
 myextraction=myextraction.[parent without children].Addtochildren(myextraction)
}

有更简单的方法吗? (可能是一种内置方法?)

1 个答案:

答案 0 :(得分:1)

您可以Linq使用Xml并执行此操作。

XDocument doc = XDocument.Load(filepath);
doc.Descendants()  
   .Where(x=>x.Attribute("id") != null && x.Attribute("id").Value == "NotNeeded")
   .Remove();

输出:

 <root>
  <level1 id="Needed">
    <level2 id="Needed">
      <level3 id="Needed">I need this one</level3>
    </level2>
  </level1>
</root>

选中此fiddle