Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to an xml file in C#

Tags:

c#

file

xml

I have an XML file formatted like this:

<Snippets>   <Snippet name="abc">     <SnippetCode>       testcode1     </SnippetCode>   </Snippet>    <Snippet name="xyz">     <SnippetCode>            testcode2     </SnippetCode>   </Snippet>    ...  </Snippets> 

I can successfully load the elements using XDocument, but I have trouble adding new elements (there are many functions and most of which I tried didn't work well for me). How would this be done? The new element would contain the snippet name tag and the snippet code tag. My previous approach was to open the file, and manually create the element using a string which although works, is a very bad idea.

What I have tried:

XDocument doc = XDocument.Load(spath); XElement root = new XElement("Snippet"); root.Add(new XElement("name", "name goes here")); root.Add(new XElement("SnippetCode", "SnippetCode")); doc.Element("Snippets").Add(root); doc.Save(spath); 

And the result is this:

<Snippet>     <name>name goes here</name>     <SnippetCode>     code goes here     </SnippetCode> </Snippet> 

It works fine except that the name tag is generated incorrectly. It should be

<Snippet name="abc">  

but I can't generate that properly.

like image 912
rayanisran Avatar asked Oct 28 '11 15:10

rayanisran


People also ask

How do I add data to an XML file?

To insert data into an XML column, use the SQL INSERT statement. The input to the XML column must be a well-formed XML document, as defined in the XML 1.0 specification. The application data type can be an XML, character, or binary type.

Which class is used in C for writing an XML file?

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items.

How do I add XAttribute to XElement?

XElement myelement = new XElement("myelement"); myelement. Add(new XAttribute("attributename", "attributevalue"); Console. WriteLine(myelement);


1 Answers

You're close, but you want name to be an XAttribute rather than XElement:

 XDocument doc = XDocument.Load(spath);   XElement root = new XElement("Snippet");   root.Add(new XAttribute("name", "name goes here"));   root.Add(new XElement("SnippetCode", "SnippetCode"));   doc.Element("Snippets").Add(root);   doc.Save(spath);  
like image 75
Jim Wooley Avatar answered Sep 21 '22 20:09

Jim Wooley