I have a simple class that essentially just holds some values. I have overridden the ToString() method to return a nice string representation.
Now, I want to create a ToXml() method, that will return something like this:
<Song> <Artist>Bla</Artist> <Title>Foo</Title> </Song>
Of course, I could just use a StringBuilder here, but I would like to return an XmlNode or XmlElement, to be used with XmlDocument.AppendChild.
I do not seem to be able to create an XmlElement other than calling XmlDocument.CreateElement, so I wonder if I have just overlooked anything, or if I really either have to pass in either a XmlDocument or ref XmlElement to work with, or have the function return a String that contains the XML I want?
You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a
ToXML()method on every class that is essentially just a Data Transfer Object.I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.
Here’s a couple of examples that Google returned:
XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf
How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx
Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx