daniel2078
daniel2078

Reputation: 33

C# Serialization not serializing datatype datetime, only strings

I have a XSD that I used to create my class. When I get the XML output, all my datetime datetypes are not serialized. I'm not getting any errors when serializing. I used the ShipDate for the samples. I don't know if the Schema Tool is adding some properties that are affecting the process. For example, ShipDateSpecified with XMLIgnoreAttribute.

thanks in advance

c#

shipHdr.TradingPartnerId = "000ALLTESTID";
shipHdr.ShipmentIdentification = "321654987";
shipHdr.ShipDate = Convert.ToDateTime("2016-03-23");
shipHdr.CarrierProNumber = "895934589485948353";
shipHdr.AppointmentNumber = "24601";

Shipment Class

private System.DateTime shipDateField;
private bool shipDateFieldSpecified;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
public System.DateTime ShipDate {
    get {
        return this.shipDateField;
    }
    set {
        this.shipDateField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ShipDateSpecified {
    get {
        return this.shipDateFieldSpecified;
    }
    set {
        this.shipDateFieldSpecified = value;
    }
}

XML Output

 <ShipmentHeader>
      <TradingPartnerId>000ALLTESTID</TradingPartnerId>
      <ShipmentIdentification>321654987</ShipmentIdentification>
      <CarrierProNumber>895934589485948353</CarrierProNumber>
      <AppointmentNumber>24601</AppointmentNumber>
  </ShipmentHeader>

Upvotes: 2

Views: 1158

Answers (2)

Scott Hannen
Scott Hannen

Reputation: 29207

Do you need an element? If you mark it as an attribute it will be serialized.

[XmlAttribute(DataType = "date")]
public System.DateTime ShipDate { get; set; }

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26446

You'll have to manually set ShipDateSpecified. The XSD probably specifies that this is an optional element.

The XmlSerializer secretly checks for a <ElementName>Specified property before it attempts to serialize <ElementName>.

If you always specify a ShipDate you can simply remove the ShipDateSpecified property.

Upvotes: 4

Related Questions