Simon Keep
Simon Keep

Reputation: 10002

How do I serialize an object into an XDocument?

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.

Upvotes: 27

Views: 27566

Answers (2)

Mark Homer
Mark Homer

Reputation: 1035

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());

Upvotes: 4

marklam
marklam

Reputation: 5358

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());

Upvotes: 47

Related Questions