Replacing a string in a xml doc with C#

What I want to do is to replace a string in a xml doc. right now my xml doc looks like this:

<?xml version="1.0"?>
<Data>
  <Player id="1">
    <name>TestName</name>
  </Player>
</Data>

What I want to do now, is to replace TestName with another string.

I have a method that looks like this, but I’m not sure if I’m going in the right direction, could really use some help getting this right.

void WriteXML(string xmlData)
{

    string name = "NewPlayer";
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(new StringReader(xmlData));
    XmlNode node = xmlDoc.SelectSingleNode("data/player/name");

    //DO something to replace the innnertext of the node with a new string
    // It is here I could use some help.

    xmlDoc.Save(xmlData);

 }

Some help would really be appriciated. Thanks in advance.

its kind of funny that you answered your own question…

node.InnerText = “NewName”

I know thats what I should do. But I’m not sure how to do it. if I just do node.InnerText = “NewName”… I get an exception object not set to an instance of an object…

Its not funny, its fantastic. People looking for solutions before asking!

touche!

Well that just means your node is null, ie. you havnt actually found the node correctly…

Ok, I fixed that issue, I changed the innertext of the node. But how do I write the new node back to the xml file? When I change the nod like that it just changes the innertext of the node but I guess I need to write the info in the xml file before I can save it.

Did you look at the file after this line?

xmlDoc.Save(xmlData);

I dont see why that wouldnt have saved the change, of course I am assuming that xmlData is a path.

Hello guys,

I am having similar problem like above mentioned.

public static string XmlMessageWriter(string xmlData, string[] xmlNodeNames, List<string> xmlNewValues)
    {
        string data = xmlData;
        Debug.Log("Before Editing" + data);

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(data);

        for (int i = 0; i < xmlNodeNames.Length; i++)
        {
          
            // edit xml child nodes with new values.  
            doc.SelectSingleNode("//" + xmlNodeNames[i]).InnerXml = xmlNewValues[i];
           // Child nodes names and new values come from method parameter above
                   
        }
        Debug.Log("After Editing" + data);
        return data;
    }

This method does 3 things:

  1. get xml data as a parameter
  2. edit its values
  3. return back after editing.

Problem is returned variable was not edited even though it was edited in the for loop.
I think I am using xml string not xml file. I found some solutions but all of them for xml file not xml string (xml file can be saved by using xml.Save method).

Can anybody suggest any solutions please?

This is the solutions for question above which I asked:

https://stackoverflow.com/questions/6161159/converting-xml-to-string-using-c-sharp