I have a class that is marked with DataContract attributes and I would like to create an XDocument
from objects of that class. Whats the best way of doing this?
I can do it by going via an XmlDocument
but this seems like an unnecessary step.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
C# Serialize ListSerialize a List with the Serializable attribute. List, serialize. In C# programs we often need to read and write data from the disk. A List can be serialized—here we serialize (to a file) a List of objects.
You can create an XmlWriter directly into the XDocument:
XDocument doc = new XDocument(); using (var writer = doc.CreateWriter()) { // write xml into the writer var serializer = new DataContractSerializer(objectToSerialize.GetType()); serializer.WriteObject(writer, objectToSerialize); } Console.WriteLine(doc.ToString());
this is how i do it, which gives clean xml without all the namespace stuff in it,
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); using (var writer = xdoc.CreateWriter()) { System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(objecttoserialize.GetType()); x.Serialize(writer, objecttoserialize); } Debug.WriteLine(xdoc.ToString());
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