0

I want to change the values of some Elements but my code isn't working. I have this XML-File:

<?xml version="1.0" encoding="utf-8"?>
<data>
  <application id="1">
    <applicationName>Instagram</applicationName>
    <username>test</username>
    <password>123</password>
    <info>test</info>
  </application>
</data>

And this C# Code:

string applicationName = "Test";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Data.xml");
XmlNode node = xmlDoc.SelectSingleNode("/data/application[@id='1']/applicationName");
node.InnerText = applicationName;
xmlDoc.Save("Data.xml");

What is the correct code to change the applicationName in the XML-File?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
User987123
  • 97
  • 1
  • 11
  • On behalf of all users here: thanks for posting a question with complete code and data; it is much appreciated – Marc Gravell Jun 23 '17 at 08:28
  • 2
    Possible duplicate of [How to modify existing XML file with XmlDocument and XmlNode in C#](https://stackoverflow.com/questions/2558787/how-to-modify-existing-xml-file-with-xmldocument-and-xmlnode-in-c-sharp) – Paul Karam Jun 23 '17 at 08:29
  • And an [alternative with XDocument](https://stackoverflow.com/q/18508765/60761) – H H Jun 23 '17 at 08:31
  • 2
    The code you posted works perfectly for me... are you sure you're looking at the right file? In particular, make sure you look at the output file in ./bin/debug or ./bin/release if you're looking under the solution folder. Can you define "isn't working"? – Marc Gravell Jun 23 '17 at 08:32
  • I second Marc Gravell. It works perfectly. – Palle Due Jun 23 '17 at 08:33

1 Answers1

0

Use LINQ and XDocument:

string applicationName = "Test";
XDocument xdocument = XDocument.Load("Data.xml");
var appName = xdocument.Elements("applicationName").Single();
appName.Value = applicationName;
xdocument.Save("Data.xml");

But you should add System.Xml.Linq to your using directives first.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • this is *an* approach, but ... it seems unnecessary, especially considering that the code in the question works fine – Marc Gravell Jun 23 '17 at 08:33
  • @MarcGravell BTW I would always prefer to use LINQ and `XDocument` as I can. – Salah Akbari Jun 23 '17 at 08:35
  • Sometimes that's perfectly valid - there are advantages and targeted scenarios (and equally: unsupported scenarios) to some tools, and *when folks are using an inappropriate tool*, it is totally legitimate to say "first use the right tool". In this case, however, both tools are perfectly fine and reasonable choices, and *unless there is a good, objective, stated reason*, IMO it is better to help people work with their existing *perfectly legitimate* tool choice. In this case, the code in the question already works perfectly and does the exact thing required. It literally requires zero changes. – Marc Gravell Jun 23 '17 at 08:38