如何序列化XDocument对象?

use*_*195 6 .net c# 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
Run Code Online (Sandbox Code Playgroud)

尝试序列化时,我得到以下异常XDocument.是否有任何方法可以使XDocument类Serializable,还是有另一种方式发送我XDocument?

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

Hen*_*man 9

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

但您可以简单地编写它们:signup_xml_file.Save(client.GetStream());
这也消除了序列化程序开销.

编辑:

另一方面,你需要

var doc = XDocument.Load(someStream);
Run Code Online (Sandbox Code Playgroud)

  • 不,另一方可以轻松地从Stream加载它.请参见编辑.不需要Serializer不需要的文件. (2认同)