C# 如何将对象序列化为 XDocument?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/806095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:57:17  来源:igfitidea点击:

How do I serialize an object into an XDocument?

c#xml-serialization

提问by Simon Keep

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?

我有一个用 DataContract 属性标记的类,我想从该类的对象创建一个 XDocument。这样做的最佳方法是什么?

I can do it by going via an XmlDocument but this seems like an unnecessary step.

我可以通过 XmlDocument 来完成,但这似乎是不必要的步骤。

采纳答案by marklam

You can create an XmlWriter directly into the XDocument:

你可以直接在 XDocument 中创建一个 XmlWriter:

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