如何序列化XDocument对象?

时间:2011-10-09 21:48:40

标签: c# .net xml serialization

我想序列化一个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类可序列化,还是有另一种方式来发送我的XDocument

  

在Assembly'System.Xml.Linq,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'中键入'System.Xml.Linq.XDocument'未标记为可序列化。

3 个答案:

答案 0 :(得分:9)

XDocuments不是为了序列化。在某种程度上,它们本身就是序列化器。

但你可以简单地写出来:signup_xml_file.Save(client.GetStream());
这也消除了串行器开销。

编辑:

另一方面,你需要

var doc = XDocument.Load(someStream);

答案 1 :(得分:2)

我没有看到您为什么要序列化XDocument对象的任何原因。只需通过调用文档上的ToString()序列化您可以获得的XML字符串。

我认为没有任何理由在这里使用二进制序列化。如果您实际上不需要它,则可以将XML字符串写入输出。

答案 2 :(得分:2)

如果您想要更好地控制XDocument的序列化,请使用WriteTo功能并创建自己的XmlWriter

以下是一个例子:

using (new XmlTextWriter(stream, Encoding.UTF8) { Formatting = Formatting })
    _document.WriteTo(xmlTextWriter);