views:

716

answers:

1

In C#, how do I replace a node in an xml with another node using XmlDocument.

For E.g, consider the following xml file.

<Products>
  <Product ProdID="1">
    <Data>abc</Data>
  </Product>
  <Product ProdID="2">
    <Data>def</Data>
  </Product>
</Products>

Let us say I need to replace

  <Product ProdID="2">
    <Data>def</Data>
  </Product>

with a new node

  <Product ProdID="2">
    <Data>xyz</Data>
  </Product>
+3  A: 

You need to locate the XmlElement to be replaced in the original XmlDocument and have the new node ready as XmlNode. Then you can call ReplaceChild to replace the old node with the new node.

XmlNode product2 = document.SelectSingleNode(...);
XmlNode newNode = document.CreateElement(...);

product2.ParentNode.ReplaceChild(newNode, product2);

If you just want to change the value of the Data tag, locate the node in the XmlDocument and set the Value property:

XmlNode data = document.SelectSingleNode(...);
data.Value = "xyz";
dtb