How to (xml) serialize a uri

前端 未结 6 2299
南笙
南笙 2020-12-18 20:02

I have a class I\'ve marked as Serializable, with a Uri property. How can I get the Uri to serialize/Deserialize without making the property of type string?

6条回答
  •  时光取名叫无心
    2020-12-18 20:37

    Based on one of the answers for how to serialize TimeSpan I ended up with this which works quite well for me and doesn't require the additional property:

    public class XmlUri : IXmlSerializable
    {
        private Uri _Value;
    
        public XmlUri() { }
        public XmlUri(Uri source) { _Value = source; }
    
        public static implicit operator Uri(XmlUri o)
        {
            return o == null ? null : o._Value;
        }
    
        public static implicit operator XmlUri(Uri o)
        {
            return o == null ? null : new XmlUri(o);
        }
    
        public XmlSchema GetSchema()
        {
            return null;
        }
    
        public void ReadXml(XmlReader reader)
        {
            _Value = new Uri(reader.ReadElementContentAsString());
        }
    
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteValue(_Value.ToString());
        }
    }
    

    Then you can use it like this

    public class Settings
    {
         public XmlUri Uri { get; set; }
    }
    
    ...
    var s = new Settings { Uri = new Uri("http://www.example.com") };
    

    And it will nicely serialize and deserialize.

    Note: Can't use the trick with the XmlElement(Type = typeof(...)) attribute as given in another answer in the above linked question as the XmlSerializer checks for an empty default constructor first on the original type.

提交回复
热议问题