且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何用c#中的新元素替换xml元素

更新时间:2023-01-21 15:56:21

通过 XML-DOM API 替换节点(XmlDocument 等):

To replace a node via the XML-DOM API (XmlDocument et al):

  1. 获取 XmlNode 的实例(或一个子类),parent,表示要替换的节点的父元素.
  2. 使用parent.RemoveChild 删除旧节点.
  3. 使用parent.AppendChild 添加新节点.
  1. Get an instance of XmlNode (or a subclass), parent, representing the parent element of the node you want to replace.
  2. Use parent.RemoveChild to remove the old node.
  3. Use parent.AppendChild to add the new node.

(作为 #3 的替代方案,请使用 parent.InsertAfterparent.InsertBefore 和对另一个子节点的引用,以将新节点放置在其他现有子节点之间.)

(As an alternative to #3 use parent.InsertAfter or parent.InsertBefore and a reference to another child to place the new node amongst other existing children.)

您在问题中编写的代码似乎是从头开始构建一个新的 XML 文档:为什么要替换节点——只需第一次创建正确的节点即可.要修改现有的 XML 文档,请使用静态 XmlDocument.Load 方法加载和解析现有文档,使用各种搜索和导航方法获取上面#1 中的引用,然后应用上述步骤,最后正常保存.

You code in the question appears to be constructing a new XML document from scratch: why would you want to replace a node—just create the right one first time. To modify an existing XML document use one of the static XmlDocument.Load methods to load and parse the existing document, use the various search and navigation methods to get the reference in #1 above, then apply the above steps, and finally save as normal.