使用Linq to XML递归删除xml节点 [英] Recursively remove xml nodes using Linq to XML

查看:68
本文介绍了使用Linq to XML递归删除xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Linq to XML的新手.如何删除 xml节点(使用关系递归)并保存文档.

Fairly new to Linq to XML How does one remove xml node( recursively using relation ) and save the document.

由于来自服务的xml的结构无法更改.下面是任务服务的xml.每个任务可以具有嵌套任务,对于这些任务可能有一个或多个嵌套任务.嵌套的目的是达到N level.

Structure of the xml cannot be altered as it comes from service.Below is the xml from a tasks service. Every task can have nested tasks for which there might be one or more nested tasks. Nesting is intended to be upto N level.

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

  • When one of parent tasks are removed using linq to xml how do i remove all of it's children?

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

How do i know all the nodes where successfully removed?

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,因此也应删除其子任务45.

In above xml when taskId=2 is removed, it's sub-tasks namely Id = 3 should be removed. Since 3 is removed it's subtasks 4 and 5 should be removed as well.

推荐答案

我将假定使用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,这是一种解决方案:

If Task ID=2 is removed, here is one solution:

// 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>

这篇关于使用Linq to XML递归删除xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆