Change one XML attribute in C #

I have an XML doc entry and it will look something like this.

<Team>
  <Character Name="Bob" Class="Mage"/>
  <Character Name="Mike" Class="Knight"/>
</Team>

I am trying to find a way to access the "Class" attribute of a single character and change it. So far, I got this to the point that I can define a specific character, but I cannot figure out how to access the Class attribute and change it for char.

void Write(string path, string charName, string varToChange, string value){

    XmlNode curNode = null;
    XmlDocument doc = new XmlDocument();
    doc.Load(path);

    XmlElement rootDoc = doc.DocumentElement;
    curNode = rootDoc;

    if(curNode.HasChildNodes){

        for(int i=0; i<curNode.ChildNodes.Count; i++){

            if(charName == curNode.ChildNodes[i].Attributes.GetNamedItem("Name").Value){

                // Code would go here
            }
        }
    }
    return;
}
+3
source share
2 answers

Use XmlElement.SetAttribute (method 'attribute to modify', 'value to set to to')

, XMLNode XMLElement, , , XmlNode XmlElement, ,

XmlElement el = (XmlElement)curNode;
el.SetAttribute("Class", "Value");

, :

XmlAttribute attrib =
curNode.OwnerDocument.CreateAttribute("Class");
attrib.Value = "Value";
curNode.Attributes.Append(attrib);

,

+3

XPATH:

XmlDocument doc = new XmlDocument();
doc.Load(path);

var nodes = doc.SelectNodes(String.Format("/Team/Character[@Name=\"{0}\"]", charName));

foreach (XmlElement n in nodes)
{
    n.SetAttribute(varToChange, value);
}
+3

Source: https://habr.com/ru/post/1754059/


All Articles