Reputation: 41
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;
}
Upvotes: 4
Views: 18888
Reputation: 6219
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);
}
Upvotes: 4
Reputation: 2268
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
Upvotes: 3