Groups | Blog | Home
all groups > dotnet xml > july 2004 >

dotnet xml : XmlSerializer for optional xs:date


dmessenger NO[at]SPAM verdantsys.com
7/21/2004 9:45:59 AM
I have several elements that have optional child elements and
attributes that are xs:dates.
I have been using System.DateTime and the XmlAttribute/XmlElement
attributes, but these will never work as System.DateTime can never be
null.

So
public class MyClass
{
[XmlAttribute("a")] public string a;
[XmlElement(ElementName="b", DataType="date")] public DateTime b;
}

will return
<MyClass>
<b>0001-01-01</b>
</MyClass>

when I want an empty element.
I have tried my own class (Date) that exposes an XmlText attribute:

public class Date
{
private string dt;
public Date() { }
[XmlText()]
public string Value { get { return dt;} set { dt=value;}}
}

and changed my class to:

public class MyClass
{
[XmlAttribute("a")] public string a;
[XmlElement(ElementName="b")] public Date b;
}

....but the serializer then throws an exception :

"Cannot serialize member 'b'. XmlAttribute/XmlText cannot be used to
encode complex types."

Dominic Messenger
7/23/2004 11:12:03 AM
Thanks. This is just what I needed.
Unfortunately, the XmlSerializer doesn't have a wealth of examples, so
finding out these things takes time.

Dominic



*** Sent via Developersdex http://www.developersdex.com ***
Dino Chiesa [Microsoft]
7/23/2004 12:19:34 PM
Hey Dominic,
There is a feature in the .NET XML Serialization engine that allows you to
optionally serialize value types, in other words, types that cannot take the
value null. Such types include bool, int, float, and DateTime, to name just
a few.

For the doc on this, see
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemXmlSerializationXmlSerializerClassTopic.asp

Here is a prior thread on the issue (May 2004)
http://tinyurl.com/4lge9

And here is an example illustrating the point for you
http://www.winisp.net/cheeso/srcview.aspx?dir=xml-serialization&file=DateOptional.cs

-D


[quoted text, click to view]

Dino Chiesa [Microsoft]
7/27/2004 6:34:54 PM
I feel your pain....
And this feature is particularly obscure and poorly documented.

-D


[quoted text, click to view]

AddThis Social Bookmark Button