简体   繁体   中英

How do you open an XML file and append data to it?

What is the best way to open an existing xml file and append a section to it?

Here is my non-working code:

XDocument usersDoc = XDocument.Load(@"Users.xml");

XElement userInfo =
new XElement("Users",
    new XElement("User",
    new XElement("ScreenName", ScreenNameTB.Text),
    new XElement("Key", KeyTB.Text),              
    new XElement("UserID", UserIdTB.Text)));
usersDoc.Add(userInfo);
usersDoc.Save(@"Users.xml");

I believe my error (if I'm on the right path) is in the usersDoc.Add(userInfo) line. But I may be off base entirely.

Thanks in advance!

You need to use the XmlDocument.CreateElement to do it like that.

Serialisation or XmlWriter would be a lot less code, and you wouldn't have to load the entire document into memory to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM