Reputation: 179
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",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
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.
Upvotes: 8
Views: 14525
Reputation: 310897
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);
Upvotes: 2
Reputation: 273244
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);
Upvotes: 10
Reputation: 244777
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.
Upvotes: 2