[英]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.我有一个标有 DataContract 属性的类,我想从该类的对象创建一个
XDocument
。 Whats the best way of doing this?这样做的最佳方法是什么?
I can do it by going via an XmlDocument
but this seems like an unnecessary step.我可以通过
XmlDocument
来做到这一点,但这似乎是一个不必要的步骤。
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());
this is how i do it, which gives clean xml without all the namespace stuff in it,我就是这样做的,它提供了干净的 xml,其中没有所有命名空间的东西,
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.