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
Related Q & A:
- How to add tabs to a toolbar?Best solution by Yahoo! Answers
- how to parse a xml file using jquery and phonegap?Best solution by Stack Overflow
- How to convert a HTML file to XML file?Best solution by Stack Overflow
- How to combine files into a RAR file?Best solution by smallbusiness.chron.com
- How to add Yahoo as a home page?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.