[英]How does one serialize an XDocument object?
我想序列化一个XDocument
对象。 我写了这段代码。
XDocument signup_xml_file = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("signup_xml_file"),
new XElement("Student",
new XElement("univ_id", univ_id),
new XElement("personal_id",personal_id),
new XElement("user_name", user_name)));
client.Connect(host_name, port);
//connect to the server .
bf.Serialize(client.GetStream(), signup_xml_file); // serialize the signup_xml_file
尝试序列化XDocument
时出现以下异常。 有没有办法让XDocument
类Serializable,还是有另一种方式来发送我的XDocument
?
在Assembly'System.Xml.Linq,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'中键入'System.Xml.Linq.XDocument'未标记为可序列化。
XDocuments不是为了序列化。 在某种程度上,它们本身就是序列化器。
但你可以简单地写它们: signup_xml_file.Save(client.GetStream());
这也消除了串行器开销。
编辑:
另一方面,你需要
var doc = XDocument.Load(someStream);
如果您想要更多地控制XDocument
序列化,请使用WriteTo
函数并创建自己的XmlWriter
。
这是一个例子:
using (new XmlTextWriter(stream, Encoding.UTF8) { Formatting = Formatting })
_document.WriteTo(xmlTextWriter);
我没有看到任何你想要序列化XDocument
对象的原因。 只需通过调用文档上的ToString()
来序列化您可以获得的XML字符串。
而且我认为没有任何理由在这里使用二进制序列化。 如果您实际上不需要它,则可以将XML字符串写入输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.