从选定的父节点删除子节点,但不删除子节点

时间:2014-08-30 06:57:51

标签: c# xml

任何人都可以帮我删除内部xml标记   我想删除fn-group和fn id标签   但我希望它的孩子p,p和强调标签应该保留

这是我的示例xml文件

     <table-wrap-foot>
     <fn-group type="footnotes">
     <fn id="c89520-1-12">
     <p>
     <emphasis type="italic">Note</emphasis>:
     In 1300, of the twenty-two cities in Italy that had populations over 20,000.
     </p>
     </fn>
     </fn-group>
     </table-wrap-foot>
     </table-wrap>

这是我的C#代码

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load("sample.xml");
        XmlNodeList xmlnode = myXmlDocument.GetElementsByTagName("table-wrap-foot");

        for (int i = 0; i < xmlnode.Count; i++)
         {
             if(xmlnode[i].InnerXml.Contains("<label>"))
             {  
             }
             else
             {
                 #here i want to delete //fn-group and fn but not p tag
             }
             }
        myXmlDocument.Save("sample.xml");

我想删除fn-group和fn id标签         但我希望它的孩子p,p和强调标签应该保留         这是我的示例xml文件
            谢谢             APPU

2 个答案:

答案 0 :(得分:0)

您可以选择<fn-group>并将其从父节点中删除,然后选择<p>并将其添加到父节点以使其保留(为了简洁,跳过null检查):

XmlNodeList xmlnode = myXmlDocument.GetElementsByTagName("table-wrap-foot");
foreach (XmlNode node in xmlnode)
{
    if (node.InnerXml.Contains("<label>"))
    {
    }
    else
    {
        var fnGroup = node.SelectSingleNode(".//fn-group");
        var p = node.SelectSingleNode(".//p");
        //remove <fn-group> from it's parent
        node.RemoveChild(fnGroup);
        //append <p> to <table-wrap-foot>
        node.AppendChild(p);
    }
}

答案 1 :(得分:0)

如果你可以使用Linq-To-Xml:

XElement root = XElement.Load(file);
XElement fnGroup = root.Descendants("fn-group").First(); // or .Element("fn-group"); if fn-group is a child of root
fnGroup.Parent.Add(fnGroup.Element("fn").Elements());    
fnGroup.Remove();
root.Save(file);

结果:

<table-wrap-foot>
  <p>
    <emphasis type="italic">Note</emphasis>:
        In 1300, of the twenty-two cities in Italy that had populations over 20,000.
  </p>
</table-wrap-foot>