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来实现,但这似乎是一个不必要的步骤。
1 个解决方案
#1
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());
#1
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());