How do I serialize an object into an XDocument?

前端 未结 1 502
不思量自难忘°
不思量自难忘° 2020-12-10 10:38

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?

相关标签:
1条回答
  • 2020-12-10 11:26

    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());
    
    0 讨论(0)
提交回复
热议问题