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();

                }

            }

1 comments:

Radley Co Tad

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.