Tuesday, July 29, 2008

.Net XmlSerializer problems with System.Uri

So, I was trying to use the XmlSerializer with some custom objects and ran into a problem with xs:anyUri being mapped to System.Uri.

The error you get when Deserializing is

Exception: System.InvalidOperationException
Message: System.Uri cannot be serialized because it does not have a default public constructor.

A quick search turns up an old issue report from Microsoft that basically says they aren't going to fix it, ever. Their excuse was it is supported with DataContract objects, but they don't support Attributes for serialization (why, I'll never know), so I can't use them in all cases.

My fix was to specify the DataType and Type elements on the XmlElement attribute. This forces a string used in the Serialization and Deserialization process, but still specifies the type of xs:anyUri for schema validation.


            private string _web;

            [XmlElementAttribute(ElementName="web", DataType="xs:anyURI", Type=typeof(string))]

            public virtual string Web

            {

                get

                {

                    return this._web;

                }

                set

                {

                    this._web = value;

                }

            }

 

            [XmlIgnore()]

            public virtual Uri WebUri

            {

                get

                {

                    return new Uri(this.Web);

                }

                set

                {

                    this.Web = value.ToString();

                }

            }

0 comments: