4

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

2 Answers 2

4

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

2 Comments

XML gets about 10 times easier to work with once you understand XPath.
What would it be with XDocument?
3

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

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.