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.
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.
The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items.
XElement myelement = new XElement("myelement"); myelement. Add(new XAttribute("attributename", "attributevalue"); Console. WriteLine(myelement);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With