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

1

7

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.

Burnie answered 14/9, 2012 at 18:10 Comment(3)
Start by using XDocument, not XmlDocument. Unless you're still using Fx 2.Favian
It is too late for me to stop using XmlDocument. I have done way too much with it already. Thanks for the suggestion thoughBurnie
Have it your way. XAttribute.Value is simply writeable.Favian
D
24

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";
Deceptive answered 14/9, 2012 at 18:21 Comment(1)
SetAttribute works even if the attribute isn't presentPilot

© 2022 - 2024 — McMap. All rights reserved.