How to dynamically change attribute of an xml node with c#

13,932

Cast your node to an XmlElement and use the element.SetAttribute(...); method.

((XmlElement)node).SetAttribute("name", "value");

Also I believe there is a way to do it without the cast if you know the attribute already exists:

node.Attributes["name"].Value = "value";
Share:
13,932
user1546315
Author by

user1546315

Updated on July 06, 2022

Comments

  • user1546315
    user1546315 almost 2 years

    I have a c# application that saves user's data to an xml document. I want to be able to dynamically change the attribute of an xml node based on a user entering different criteria into a text box and choosing to save/overwrite the existing file save. The problem is that I can't simply delete the node and recreate it with the new attribute as the node has child nodes that can't be deleted.

    Does anyone have any ideas or suggestions?

    the XmlNode.Attributes method does not provide a way as I can tell to delte just the attribute of a node and reassign it. I could be wrong though.

  • C.M.
    C.M. almost 7 years
    SetAttribute works even if the attribute isn't present