我将假设使用 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>