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>

1 Answer 1

5

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.