开发者

How does one serialize an XDocument object?

I want to serialize an XDocument object. I wrote this code.

        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",p开发者_如何学Goersonal_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

I get the following exception when attempting to serialize the XDocument. Is there any way to make the XDocument class Serializable, or is there another way to send my XDocument?

Type 'System.Xml.Linq.XDocument' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.


XDocuments are not intended to be serialized. In a way they are serializers themselves.

But you can simply write them: signup_xml_file.Save(client.GetStream());
which also eliminates serializer overhead.

Edit:

And on the other side you will need

var doc = XDocument.Load(someStream);


I don't see any reason why you'd want to serialize the XDocument object. Just serialize the XML string that you can get by calling ToString() on the document.

And I don't see any reason to use binary serialization here at all. If you actually don't need it, you can just write the XML string to the output.


If you want more control over serialisation of XDocument, use the WriteTo function and create your own XmlWriter.

Here's an example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜