对 Linq to XML 相当陌生 如何删除 xml 节点(递归使用关系)并保存文档。
xml 的结构不能更改,因为它来自服务。下面是来自任务服务的 xml。每个任务都可以有嵌套任务,其中可能有一个或多个嵌套任务。嵌套旨在达到 N 级
。
当使用 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>
在上面的 xml 中,当 taskId=2
被移除时,它的子任务即 Id = 3
应该被移除。由于 3
已被删除,因此它的子任务 4
和 5
也应被删除。
最佳答案
我将假设使用 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>
关于c# - 使用 Linq to XML 递归删除 xml 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378498/