从选定的父节点中移除子节点,但不移除子节点
本文关键字:子节点 父节点 | 更新日期: 2023-09-27 18:20:12
任何人请帮助我删除内部xml标记我想删除fn组和fn id标签的位置但我希望它的子标签p,p和emphasis应该保留
这是我的示例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组和fn id标签的位置但我希望它的子标记p、p和emphasis应该保留这是我的示例xml文件
谢谢Appu
如果可以使用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>
您可以选择<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);
}
}