-1

I tried to update this small xml example file without success. It is not giving me any error but the file remains unchanged. Any ideas ?

Thanks

XML Sample:

<test>
  <user>John Doe</user>
  <user>Jane Doe</user>
</test>

C# Code

 XmlDocument doc = new XmlDocument();
    doc.Load("../../../test.xml");

    XmlNode sNode = doc.SelectSingleNode("/test/user");
    XmlAttribute users = sNode.Attributes["user"];

    if (users != null)
    {             
            string currentValue = users.Value;            
            if (string.IsNullOrEmpty(currentValue))
            {
            users.Value = "Thomas";
            }
    }
    doc.Save("../../../test1.xml");
Thomas
  • 69
  • 2
  • 11

3 Answers3

1

This is how I changed the value inside a node:

        XmlNode node= _doc.SelectSingleNode("test/user[1]"); // [index of user node]
        node.InnerText = value;
        _doc.Save(@"path");
Timon Post
  • 2,779
  • 1
  • 17
  • 32
1

This works now perfectly:

XmlDocument doc = new XmlDocument();
doc.Load("../../../test.xml");

XmlNode node = doc.SelectSingleNode("test/user[1]"); // [index of user node]
node.InnerText = "thomas";

doc.Save("../../../test1.xml");

Thank you

Thomas
  • 69
  • 2
  • 11
0

Your user node doesn't have any attribute in your XML file :

So users is null here :

 XmlAttribute users = sNode.Attributes["user"];

You should test if sNode != null

 if (sNode != null){
    ....
 }
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
  • Thank you, I just noticed that I don`t have an attribute there, but the solution from Timon Post was what I was looking for and it works perfectly. – Thomas Sep 15 '16 at 19:54