When writing/reading XML in vbScript, everything was easy because I could refer to nodes like an array (ex: main_node.sub_node). I am learning C#, and am having problems with XML. All books and resources show me how to write a full file. What if I want to change the value of one element? Let's say I have the following XML file:
Given the program knows the name "Redlehk", how would you go about reading in his age, and then writing back to the XML file a new age. If anyone can show me how this is done, or point me to a resource, I would greatly appreciate it.
Here is one way to do it.
Suppose the XML file looks like this:
Then this will work:
<?xml version="1.0" encoding="UTF-8"?>
Hope that helps.
static void Main(string args)
// Load the Xml document
XmlDocument xmlDoc = new XmlDocument();
// Create an XmlTextWriter from the document
XmlTextWriter writer = new XmlTextWriter("person.xml", null);
writer.Formatting = Formatting.Indented;
// Loop through each person
XmlNodeList personList = xmlDoc.GetElementsByTagName("person");
for(int i = 0; i < personList.Count; i++)
XmlElement person = (XmlElement) personList[i];
// Get the person's name
XmlNodeList personNameList = person.GetElementsByTagName("name");
XmlElement personName = (XmlElement) personNameList;
// Get the person's age
XmlNodeList personAgeList = person.GetElementsByTagName("age");
XmlElement personAge = (XmlElement) personAgeList;
// Compare the data
if (personName.InnerText == "Redlehk")
personAge.InnerText = "44";
// Write the changes
That is exactly what I was looking for. Thank you. Ill try and implement it into my real project tonight, and I'll be back if I have some more questions.