从保留标记的XML节点中删除所有子节点

时间:2017-01-11 15:46:59

标签: c# xml linq

我正在制作一个“简单”程序来更新xml文件。

XML代码段

<statistics>
    <offices location=”city1” >
        <office name=”office1”/>
        <office name=”office2”/>
    </offices>
    <offices location=”city2” >
        <office name=”office3”/>
        <office name=”office4”/>
    </offices>
</statistics>

我的事件序列是:

  1. 将xml加载到树视图中

  2. 删除一些孩子,添加一些孩子,在树视图中的父母之间移动一些。

  3. 删除xml中的所有子项。

  4. 遍历树视图并将子项添加回xml。

  5. 保存文件。

  6. 问题在于,当我删除所有子项时,</offices>标记被删除以保持完整性,我留下了

    <offices location=”city1” />
    <offices location=”city2” />
    

    如果我现在插入新办公室

    <offices location=”city1” />
    <office name=”office1”/>
    <office name=”office2”/>
    <offices location=”city2” />
    <office name=”office3”/>
    <office name=”office4”/>
    

    有没有办法删除孩子并保留</offices>标签,或者我是否认为这一切都错了? 谢谢你的帮助, 格里。

    这就是我删除孩子的方式

    private void deleteAllOffices(XDocument doc)
    {
       var offices = doc.Root.Descendants("offices").ToList();
       foreach (var factor in offices)
       {
            var location = factor.Attribute("location").Value;
            // Delete the children
            deleteChildren(doc, location);
        }
    }
    private void deleteChildren(XDocument doc, string catg)
    {
        var lv1s = from lv1 in doc.Descendants("offices")
                   where lv1.Attribute("location").Value.Equals(catg)
                   select new
                   {
                       Children = lv1.Descendants("office")
                   };
    
        //Loop through results
        foreach (var lv1 in lv1s)
        {
           foreach (var lv2 in lv1.Children.ToArray())
             lv2.Remove();
        }
    }
    

    这就是我将办公室添加回xml的方式

    // First delete all the offices
    deleteAllOffices(doc);
    // Now add the offices from the treeview
    //Create a TreeNode to hold the Parent Node
    
    TreeNode temp = new TreeNode();
    //Loop through the Parent Nodes
    for (int k = 0; k < treeView1.Nodes.Count; k++)
    {
       //Store the Parent Node in temp
       temp = treeView1.Nodes[k];
    
       //Now Loop through each of the child nodes in this parent node i.e.temp
       for (int i = 0; i < temp.Nodes.Count; i++)
           {
              doc.Element("statistics")
                 .Elements("offices")
                 .Where(item => item.Attribute("location").Value == temp.Text).FirstOrDefault()
                 .AddAfterSelf(new XElement("office", new XAttribute("name", temp.Nodes[i].Text)));
           }
     }
     doc.Save(@"d:\temp\stats.xml");
    

1 个答案:

答案 0 :(得分:1)

问题在于AddAfterSelf方法:在当前节点之后添加新的XElement ,作为你需要孩子的兄弟姐妹。

您需要XElement的Add方法(或者更确切地说是XContainer)将新的XElement添加为子元素。

顺便说一下,XML <offices location="city1" /><offices location="city1"></offices>

相同