Juanjo's Blog

Dot Net Development | Technology | Xbox freak :-)

  Home :: Contact :: Syndication  :: Login
  11 Posts :: 0 Stories :: 4 Comments :: 0 Trackbacks

Archives

Post Categories

My Blog Read List

My links

Wow... Two posts in a day! Just incredible for me!!! (LOL, this is for Miguel that is always bugging me to post) :o)

As I told in the previous post, I am having difficulties when serializing to Xml with DateTime and Boolean types, because they are serialized in a format I don´t need. For example, DateTime types serialize like 2005-01-23T00:01:02.000000+02:00 (with millisecs an time zone info). I do not need this. I have workarounded this in the following way:

When you run XSD.exe with a schema, it gives you a class (or a collection of them). In each class you can find this method (for a DateTime class):

 
  ///Original method
  [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
  public System.DateTime DateDistributed 
  {
   get 
   {
    return this.dateDistributedField;
   }
   set 
   {
    this.dateDistributedField = value;
   }
  }

If you change the property to this, you can control the format the DateTime is serialized with.

 
  /// 
  /// This is the new method, I've decorated it with XmlElementAttribute attribute and the name of the original Property.
  /// The DateTime is serialized as a String, and you can control the output format for the date / time.
  /// 
  [System.Xml.Serialization.XmlElementAttribute("DateDistributed", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
  [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
  public string __DateTime_DateDistributed
  {
   get
   {
    if (this.dateDistributedField != System.DateTime.MinValue)
     return this.dateDistributedField.ToString("yyyy-MM-ddTHH:mm:ss");
    else 
     return System.String.Empty;
   }
   set
   {
    this.dateDistributedField = System.DateTime.Parse(value);
   }
  }

  /// 
  /// This is the old method, I've decorated it with XmlIgnore attribute. This makes the original property not serializing.
  /// 
  [System.Xml.Serialization.XmlIgnore()]
  public System.DateTime DateDistributed 
  {
   get 
   {
    return this.dateDistributedField;
   }
   set 
   {
    this.dateDistributedField = value;
   }
  }

Yes, I know this is not the best solution if you have a large schema (like mine), but at least I can control how I output my values to Xml.

The best solution would be change the XmlSerializer do the serialization of the types, but I didn't find out how to do it... If you know please let me know!

 

posted on Tuesday, April 26, 2005 4:56 PM