Linq to XML - 删除节点并在同一位置添加新节点
我有一个 XDocument,必须删除一个节点并在进行一些操作后再次添加完全相同的节点(我的 xelement 节点很复杂并且也有内部节点)。有没有人有一个好方法来做到这一点,因为我的新操作节点被添加到 xml 文档的最后。任何代码片段将不胜感激。
I have an XDocument and have to remove a node and add the very same node back again after some manipulation(my xelement node are complex and have inner nodes as well). Has anyone got a good way to do this as my new manipulated node is being added at the very end of the xmldocument. Any code snippets would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,这应该可以帮助你做到这一点。
SolarSystem.xml:
代码找到
Mercury,向其中添加一个额外元素,将其删除,然后将其重新插入到
的末尾收藏。这给出:
If I understand you right, this should help you do it.
SolarSystem.xml:
The code finds the
<Planet>
Mercury, adds an extra element to it, removes it, and reinserts it at the end of the<Planets>
collection.which gives:
如果您只是编辑节点,那么为什么要删除它呢?只需在树中获取对它的引用并就地编辑即可。
如果由于某种原因这不是一个选项,那么一种解决方法是:一旦找到您需要的
XElement
(或者通常是XNode
)要在树中替换,请创建一个新的XElement
作为替换,然后使用XNode.ReplaceWith
旧元素上的方法,传递新元素作为参数。If you're just editing the node, then why remove it at all? Just get a reference to it in the tree and edit it in-place.
If that's not an option for some reason, then one way to go about it is this: once you've found the
XElement
(or, in general,XNode
) you need to replace in the tree, create a newXElement
to serve as a replacement, and then useXNode.ReplaceWith
method on the old element, passing new one as the argument.这只是建立在@Ralph Lavelle 上面的例子之上。我创建了一个完整的控制台应用程序,这样我就可以使用代码和更好地理解它。我想我会分享它。它使用与上面完全相同的示例 XML,但我必须删除对 Server.MapPath() 的引用,因为我无法弄清楚如何使它们工作。给你:
也许这会帮助像我这样的另一个 LINQ 菜鸟。
This just builds on @Ralph Lavelle's example above. I created a complete console app so I could play with the code & understand it better. Figured I'd share it. It uses the exact same sample XML from above, but I had to remove the references to Server.MapPath() as I couldn't figure out how to make them work. Here you go:
Maybe this'll help another LINQ noob like me.