使用Linq to XML递归删除xml节点

时间:2012-04-30 04:28:12

标签: c# xml linq file-io linq-to-xml

Linq to XML相当新的如何删除 xml节点(递归使用关系)和保存文档。

xml的结构不能改变,因为它来自service.Below是来自任务服务的xml。每个任务都可以具有可能存在一个或多个嵌套任务的嵌套任务。嵌套最高为N level

  • 当使用linq to xml删除其中一个父任务时,如何删除所有子任务?

  • 我如何知道成功删除的所有节点?

XML:

<Tasks>
  <Task ID="1">Clean the Room</Task>
  <Task ID="2">Clean the Closet</Task>
  <Task ID="3" ParentId="2">Remove the toys</Task>
  <Task ID="4" ParentId="3">Stack action Figures on Rack</Task>
  <Task ID="5" ParentId="3">Put soft toys under bed</Task>
</Tasks>

在删除taskId=2时的上述xml中,应删除其子任务Id = 3。由于3被删除,因此也应删除子任务45

2 个答案:

答案 0 :(得分:4)

我将假设使用xml:

<Tasks> 
  <Task ID="1">Clean the Room</Task>
  <Task ID="2">Clean the Closet</Task>
  <Task ID="3" ParentId="2">Remove the toys</Task>
  <Task ID="4" ParentId="3">Stack action Figures on Rack</Task>
  <Task ID="5" ParentId="3">Put soft toys under bed</Task>

  <Task note="test node" />
  <Task ID="a" note="test node" />
</Tasks>

如果删除了Task ID=2,则这是一个解决方案:

// tasks = XDocument.root;

public static void RemoveTasksAndSubTasks(XElement tasks, int id)
{
  List<string> removeIDs = new List<string>();
  removeIDs.Add(id.ToString());

  while (removeIDs.Count() > 0)
  {
    // Find matching Elements to Remove
    // Check for Attribute, 
    // so we don't get Null Refereence Exception checking Value

    var matches = 
        tasks.Elements("Task")
             .Where(x => x.Attribute("ID") != null
                         && removeIDs.Contains(x.Attribute("ID").Value));

    matches.Remove();

    // Find all elements with ParentID 
    // that matches the ID of the ones removed.
    removeIDs = 
        tasks.Elements("Task")
             .Where(x => x.Attribute("ParentId") != null
                         && x.Attribute("ID") != null
                         && removeIDs.Contains(x.Attribute("ParentId").Value))
             .Select(x => x.Attribute("ID").Value)
             .ToList();

  }
}

结果:

<Tasks> 
  <Task ID="1">Clean the Room</Task>

  <Task note="test node" />
  <Task ID="a" note="test node" />
</Tasks>

答案 1 :(得分:1)

使用以下答案

XDocument doc = XDocument.Load("task.xml");
var q = from node in doc.Descendants("Task")
        let attr = node.Attribute("ID")
        let parent = node.Attribute("ParentId")
        where ((attr != null && attr.Value == "3") || (parent != null && parent.Value == "3"))
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");