【发布时间】:2013-02-04 17:06:42
【问题描述】:
我有一个关于从 xml 文件中删除特定节点的问题。
这是我的 XML 示例:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<nodeA attribute="1">
<nodeB attribute="table">
<nodeC attribute="500"></nodeC>
<nodeC attribute="5"></nodeC>
</nodeB>
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribute="5"></nodeC>
</nodeB>
<nodeB attribute="placeHolder">
<nodeB attribute="toRemove">
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
</nodeB>
</nodeB>
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribtue="5"></nodeC>
</nodeB>
<nodeB attribute="placeHolder">
<nodeB attribute="toRemove">
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
</nodeB>
</nodeB>
</nodeA>
</root>
我想删除节点nodeB="toRemove" 而不删除该节点的子节点。之后我需要对nodeB attribute="placeHolder" 做同样的事情。部分结果如下所示:
<nodeB attribute="3">
<nodeC attribute="4"></nodeC>
<nodeC attribute="5"></nodeC>
<nodeC attribtue="5"></nodeC>
</nodeB>
<nodeB attribute="glass"></nodeB>
<nodeE attribute="7"></nodeE>
<nodeB attribute="glass"></nodeB>
<nodeB attribute="glass"></nodeB>
我一直在尝试这样的代码来实现:
XmlNodeList nodeList = doc.SelectNodes("//nodeB[@attribute=\"toRemove\"]");
foreach (XmlNode node in nodeList)
{
foreach (XmlNode child in node.ChildNodes)
{
node.ParentNode.AppendChild(child);
}
node.ParentNode.RemoveChild(node);
}
doc.Save(XmlFilePathSource);
我能够找到具有所需属性 toRemove 或 placeHolder 的节点,但是我无法将此节点的子节点上移一级。在这种情况下你能帮我吗?它可以是 Linq、XDocument、XmlReader 的解决方案,但我更喜欢使用 XmlDocument。 感谢您提前为我提供的任何帮助。
编辑:
在这种情况下,我使用了 Chuck Savage 在下面编写的稍微修改过的代码(以保持顺序)。一次删除
<nodeB attribute="toRemove"> </nodeB>
然后对
做同样的事情 <nodeB attribute="placeHolder"></nodeB>
这里是稍微修改的代码
XElement root = XElement.Load(XmlFilePathSource);
var removes = root.XPathSelectElements("//nodeB[@attribute=\"toRemove\"]");
foreach (XElement node in removes.ToArray())
{
node.Parent.AddAfterSelf(node.Elements());
node.Remove();
}
root.Save(XmlFilePathSource);
@MiMo 提供的 xslt 方法在这种情况下也非常有用。
【问题讨论】:
-
您的许多
nodeC元素缺少结束标记。你能用有效的、格式正确的 xml 更新你的问题吗? -
我已经更新了我的简化 xml 文件。感谢您的提示,现在其他人更容易阅读。
标签: c# xml xpath xml-parsing linq-to-xml