0

I've an XSD with a definition for a DateTime type like this:

  <xs:simpleType name="ISODateTime">
    <xs:restriction base="xs:dateTime"/>
  </xs:simpleType>

xsd.exe generates a DateTime property for elements of this type.

        public System.DateTime dtName {
            get {
                return this.dtNameField;
            }
            set {
                this.dtNameField = value;
            }
        }

When serializing an instance of the generated class XmlSerializer converts DateTimes to a value in the format 2023-04-28T14:47:37.0001+02:00.

But I need the DateTime to be formated as YYYY-MM-DDThh:mm:ss.sssZ or YYYY-MM-DDThh:mm:ss.sss+/-hh:mm.

I cannot change the XSD nor the validation rules of the XML. Is there a way I can override how XmlSerializer formats DateTimes in the XML?

musium
  • 2,942
  • 3
  • 34
  • 67
  • There's no builtin way to do this, the best alternative is to use a surrogate string property as suggested by @jdweng. See [Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'](https://stackoverflow.com/q/3534525) and [Serializing DateTime to time without milliseconds and gmt](https://stackoverflow.com/q/101533),which look to be duplicates. – dbc Apr 28 '23 at 15:12

1 Answers1

1

The XML is text so you can treat it as a string and then convert to datetime like this

    public class Test
    {
        public System.DateTime _dtNameField { get; set; }

        public string dtName
        {
            get
            {
                return _dtNameField.ToString("Format");
            }
            set
            {
                _dtNameField = DateTime.Parse(value);
            }
        }

    }
jdweng
  • 33,250
  • 2
  • 15
  • 20