0

How can I write an XML file so that it starts a new line and does not overwrite the previous data?

string pfad = "C:\\temp\\Accounts.xml";

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Login");
XmlElement id = doc.CreateElement("user");
XmlElement username = doc.CreateElement("username");
username.InnerText = txtBenutzerName.Text;

id.AppendChild(username);

root.AppendChild(id);
doc.AppendChild(root);
doc.Save(pfad);
MessageBox.Show("Created SuccesFully!");
lloydpick
  • 1,638
  • 1
  • 18
  • 24
  • You're creating a completely new document - it sounds like you should load the existing XML file, append the new element, then save it again. – Jon Skeet Apr 18 '18 at 13:03
  • Welcome on Stacloverflow as 'original poster'. You probably do not want to create a new document. Open the existing one and add the node. Of course this has been asked before. See https://stackoverflow.com/questions/5975114/adding-new-node-to-existing-xmldocument-object . Your question will be marked as duplicate (by someone with enough reputation). – RWC Apr 18 '18 at 13:13

2 Answers2

4

Instead of creating a new document by this line

XmlDocument doc = new XmlDocument();

you should load existing file like this:

XmlDocument doc = new XmlDocument();
doc.Load(pfad);

...below code is the same...
v.karbovnichy
  • 3,183
  • 2
  • 36
  • 47
0
  XmlDocument doc = new XmlDocument();
  doc.Load("C:\\Accounts.xml");
  doc.GetElementsByTagName("username")[0].InnerText="sdkjfsdknfkds";
  doc.Save("C:\\Accounts.xml");
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Bikash
  • 29
  • 1