Modify a single XML attribute in C#

2019-04-11 00:00发布

问题:

I've got it writing the XML doc fine, and it will look something like this

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

I'm trying to find a way to access "Class" attribute of a single character and modify it. So far, i've got it to the point where I can pinpoint a specific character, but I can't figure out how to access the 'Class' attribute and modify it for the 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;
}

回答1:

Use 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);
}


回答2:

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

edit: I just noticed you were using XMLNode instead of XMLElement, so in order to update the attribute you can either just cast the XmlNode to an XmlElement like so

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

Otherwise you can create an attribute and then append it in order to update the attribute:

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

Hope this helps