12

I have created a C# class file by using a XSD-file as an input. One of my properties look like this:

 private System.DateTime timeField;

 [System.Xml.Serialization.XmlElementAttribute(DataType="time")]
 public System.DateTime Time {
     get {
         return this.timeField;
     }
     set {
         this.timeField = value;
     }
 }

When serialized, the contents of the file now looks like this:

<Time>14:04:02.1661975+02:00</Time>

Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?

<Time>14:04:02</Time>

Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?

It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.

The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.

Chris
  • 6,761
  • 6
  • 52
  • 67
Espo
  • 41,399
  • 21
  • 132
  • 159
  • Look at http://stackoverflow.com/questions/3534525/force-xmlserializer-to-serialize-datetime-as-yyyy-mm-dd-hhmmss – TNT Jan 13 '17 at 14:16

2 Answers2

24

Put [XmlIgnore] on the Time property.

Then add a new property:

[XmlElement(DataType="string",ElementName="Time")]
public String TimeString
{
    get { return this.timeField.ToString("yyyy-MM-dd"); }
    set { this.timeField = DateTime.ParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture); }
}
Matt Howells
  • 40,310
  • 20
  • 83
  • 102
  • 2
    Is `"yyyy-MM-dd"` the correct format string for a time field? While this solution didn't work for me out of the box, it did lead me to one that did. I had to use `"HH:mm:ss"`, and I sourced from my `dateField` like this `get { return this.dateField.ToString("HH:mm:ss"); }` – OutstandingBill May 18 '17 at 04:27
  • Same goes for Uri data type as well. That was my problem, and this is how I fixed it. [JsonIgnore] [XmlIgnore] public Uri UrlIgnore { get; set; } [JsonProperty("url")] [XmlElement] public string Url { get { return Convert.ToString(UrlIgnore); } set { UrlIgnore = new Uri(value); } } – fluidguid Nov 01 '18 at 20:40
14

You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.

Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99