views:

44

answers:

3

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  A: 

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

Eric U.
A: 

Element solution worked great. Thanks!

PhantomGun
Could you do Eric U a favor and mark his question as answered if his solution worked? There should be a hollow tick next to his answer - just click that.
Alex Humphrey
+1  A: 

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);
}
Alex Humphrey
XML gets about 10 times easier to work with once you understand XPath.
Robert Rossney