簡體   English   中英

如何序列化XDocument對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM