[英]how to remove all the childnodes of the specified xmlnode in C# 4.0?
这是我的 xml。
<Document>
<page no="1">
<Paragraph no="1">
<Line>line1</Line>
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
<Line>line1</Line>
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
</Document>
我的 C# 密码是
XmlDocument xd = new XmlDocument();
xd.Load(@"H:\Sample-8-final.xml");
XmlNodeList pnodelist = xd.GetElementsByTagName("page");
XmlNodeList xdChildNodeList = xd.ChildNodes;
for (int i = 0; i < pnodelist.Count; i++)
{
XmlNode pageNode = pnodelist[i];
foreach (XmlNode xxNode in pageNode.ChildNodes)
{
if (xxNode.Name.ToString().Trim().Equals("Paragraph"))
{
foreach (XmlNode yyNode in xxNode.ChildNodes)
{
yyNode.ParentNode.RemoveChild(yyNode);
}
}
}
xd.Save(@"H:\Sample-8-final_1.xml");
我需要的 output 是
<Document>
<page no="1">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
</Paragraph>
</page>
</Document>
但是我的代码产生了错误的结果,如下所示:
<Document>
<page no="1">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
</Document>
请指导我摆脱这个问题......
使用LINQ to XML删除Paragraph元素的所有后代:
XElement root = XElement.Load(@"H:\Sample-8-final_1.xml");
root.Descendants("Paragraph").Descendants().Remove();
注意:您需要using System.Xml.Linq;
在文件的顶部。
问题是您在以下几行中更改要迭代的内容:
foreach (XmlNode yyNode in xxNode.ChildNodes)
{
yyNode.ParentNode.RemoveChild(yyNode);
}
如果yyNode.ParentNode
xxNode
替换xxNode
(这xxNode
是这样), xxNode
容易发现。 这导致迭代器感到困惑,并跳过了一些您不希望这样做的事情。
尽管可能只是调用xxNode.RemoveAll()
可能更容易。 请参阅文档: http : //msdn.microsoft.com/zh-cn/library/system.xml.xmlnode.removeall
但是请注意,正如Mahen所说的那样,这也会删除您的属性,因此通常不是理想的解决方案(例如,在这种情况下也不是)。
代码没有问题,您只需要精确使用文字即可。 它们区分大小写。 写“ page”代替“ PAGE”,“ Paragraph”代替“ PARAGRAPH”,那么代码就可以了。
克里斯(Chris)解释说,迭代失败是因为您在遍历该集合时正在修改ChildNodes
(通过删除它们)。 他建议改为使用RemoveAll()
。 但是RemoveAll()
删除属性以及子元素,这不是我想要的。 这就是我写的在保留属性的同时安全地进行迭代的内容(在VB.NET中):
Private Shared Sub RemoveAllChildren(element As XmlElement)
' you can't iterate and delete in the same loop, because you would be modifying .ChildNodes
Dim childrenList = New ArrayList()
For Each child In element.ChildNodes
childrenList.Add(child)
Next
For Each child In childrenList
child.ParentNode.RemoveChild(child)
Next
End Sub
while (parentNode.ChildNodes.Count > 0)
{
parentNode.RemoveChild(parentNode.ChildNodes[0]);
}
也应该工作。
简单,只需使用 while:
while (node.HasChildNodes)
{
node.RemoveChild(node.FirstChild);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.