How Add element to XML file?

C# how to add elements to a xml file

  • I'm using WinForms .NET 2.0 for my application. Previously, I used NET 4.0 to add an element to an existing XML file in this way: XDocument doc = XDocument.Load(spath); XElement root = new XElement("Snippet"); root.Add(new XAttribute("name", name.Text)); root.Add(new XElement("SnippetCode", code.Text)); doc.Element("Snippets").Add(root); doc.Save(spath); Where spath is the path of the XML file. I am having trouble degrading this code to .NET 2.0 since the syntax is confusing, can someone help me? I'm trying to add an element with an attribute and element like this: <Snippet name="snippet name"> <SnippetCode> code goes here </SnippetCode> </Snippet> Help would be appreciated.

  • Answer:

    Try this code : XmlDocument doc = new XmlDocument(); doc.Load(spath); XmlNode snippet = doc.CreateNode(XmlNodeType.Element, "Snippet", null); XmlAttribute att = doc.CreateAttribute("name"); att.Value = name.Text; snippet.Attributes.Append(att); XmlNode snippetCode = doc.CreateNode(XmlNodeType.Element, "SnippetCode", null); snippetCode.InnerText = code.Text; snippet.AppendChild(snippetCode); doc.SelectSingleNode("//Snippets").AppendChild(snippet);

david at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.