Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize an object into an XDocument?

Tags:

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.

like image 965
Simon Keep Avatar asked Apr 30 '09 09:04

Simon Keep


People also ask

What does it mean to serialize XML?

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.

Can you serialize a List C#?

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.


2 Answers

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()); 
like image 52
marklam Avatar answered Sep 30 '22 19:09

marklam


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()); 
like image 32
Mark Homer Avatar answered Sep 30 '22 21:09

Mark Homer