Possible Duplicate:
How to (xml) serialize a uri
To my knowledge Uri
implements ISerializable, but throws error when used like this:
XmlSerializer xs = new XmlSerializer(typeof(Server));
xs.Serialize(Console.Out, new Server { Name = "test", URI = new Uri("http://localhost/") });
public class Server
{
public string Name { get; set; }
public Uri URI { get; set; }
}
Works just fine if Uri
type is changed to string
.
Anyone knows what is the culprit?
public class Server
{
public string Name { get; set; }
[XmlIgnore()]
public Uri Uri;
[XmlElement("URI")]
public string _URI // Unfortunately this has to be public to be xml serialized.
{
get { return Uri.ToString(); }
set { Uri = new Uri(value); }
}
}
(Thanks for SLaks also pointing out the backwardness of my method...)
This produces XML output:
<Server>
<URI>http://localhost/</URI>
<Name>test</Name>
</Server>
I rewrote it here so the code is visible.
In order to be serialized to XML, Uri
class should have a parameterless constructor, which it doesn't: Uri
is designed to be immutable. Honestly, I can't see why it cannot be serialized without having a parameterless constructor.
To circumvent this, either change URI
property type to string
, or add one more property called _URI
, mark URI
with XmlIgnoreAttribute
and rewrite it's get
method as get { return new Uri(_URI); }
.
You're confusing binary serialization with XML serialization.
XML serialization is a very simple process that saves field values and restores into a new object.
Binary serialization is much more powerful, and allows the object to control serialization behavior. The ISerializable interface, which Uri does implement, is only used for binary serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With