sharp serialize serializar deserialize deserializar c# .net xml-serialization

c# - serializar - XmlSerializer: la cadena '''' no es un valor válido de AllXsd



serializer c# (5)

Recibo este mensaje, "La cadena ''7/22/2006 12:00:00 AM'' no es un valor válido de AllXsd.", Al deserializar un XML, el elemento contiene una fecha, esta es la propiedad que se supone para ser asignado al elemento:

[XmlElement("FEC_INICIO_REL",typeof(DateTime))] public DateTime? FechaInicioRelacion { get; set; }

¿Estoy haciendo algo mal?

ACTUALIZACIÓN: Aquí está el XML:

<Detalle> <NOM_ASOC>Financiera Panameña</NOM_ASOC> <DESCR_CORTA_RELA>PREST. PERSONAL</DESCR_CORTA_RELA> <FEC_INICIO_REL>7/22/2006 12:00:00 AM</FEC_INICIO_REL> <FEC_FIN_REL>9/22/2008 12:00:00 AM</FEC_FIN_REL> <MONTO_ORIGINAL>1160.0000</MONTO_ORIGINAL> <NUM_PAGOS>2</NUM_PAGOS> <DESCR_FORMA_PAGO>PAGOS VOLUNTARIOS</DESCR_FORMA_PAGO> <IMPORTE_PAGO>59.9400</IMPORTE_PAGO> <FEC_ULTIMO_PAGO>11/15/2006 12:00:00 AM</FEC_ULTIMO_PAGO> <MONTO_ULTIMO_PAGO>0.0000</MONTO_ULTIMO_PAGO> <DESCR_OBS_CORTA /> <SALDO_ACTUAL>1078.3900</SALDO_ACTUAL> <NUM_DIAS_ATRASO>0</NUM_DIAS_ATRASO> <HISTORIA>1</HISTORIA> <MONTO_CODIFICADO /> <FEC_ACTUALIZACION>10/17/2008 12:00:00 AM</FEC_ACTUALIZACION> <COD_GRUPO_ECON> </COD_GRUPO_ECON> <TIPO_ASOC> </TIPO_ASOC> <NUM_REFER>2008628116</NUM_REFER> </Detalle>


AllocationDate es un campo obligatorio, pero se puede proporcionar en blanco, que se maneja representándolo con AllocationDateString:

private DateTime? _allocationDate; [XmlIgnore] public DateTime? AllocationDate { get { return _allocationDate; } set { _allocationDate = value; } } [XmlAttribute("AllocationDateTime")] public string AllocationDateTimeString { get { return _allocationDate.HasValue ? XmlConvert.ToString(_allocationDate.Value, XmlDateTimeSerializationMode.Unspecified) : string.Empty; } set { _allocationDate = !string.IsNullOrEmpty(value) ? XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Unspecified) : (DateTime?)null; } }


Intente agregar el atributo "IsNullable = true".


Me doy cuenta de que esta es una pregunta antigua, pero tuve este problema hoy y encontré una solución alternativa utilizando propiedades y casting.

private string _date; // Private variable to store XML string // Property that exposes date. Specifying the type forces // the serializer to return the value as a string. [XmlElement("date", Type = typeof(string))] public object Date { // Return a DateTime object get { return !string.IsNullOrEmpty(_date) ? (DateTime?) Convert.ToDateTime(_date) : null; } set { _date = (string)value; } }

Ahora, cuando necesite consultar la fecha, simplemente llame:

var foo = (DateTime?)Bar.Date

Ha estado funcionando bien para mí desde entonces. Si no le importa agregar el cast adicional en su código, ¡puede hacerlo de esta manera también!

Edición: debido al comentario de Dirk, decidí revisar mi implementación en una rama separada. En lugar de utilizar una clase de object , que es propensa a errores de compilación en tiempo de ejecución, devuelvo el valor como una cadena.

[XmlElement("date")] public string Date;

Lo que hace que la declaración sea mucho más simple. Pero al intentar leer desde la variable, ahora debe proporcionar comprobaciones nulas.

var foo = string.IsNullOrEmpty(Date) ? Convert.ToDateTime(Date) : (DateTime?) null

Funciona exactamente de la misma manera que la implementación anterior, excepto que las verificaciones de conversión y nulas ocurren en una ubicación diferente. Quiero poder escribir mi modelo y luego olvidarme de él, así que prefiero mi implementación en su lugar.

En otra nota, agregué una corrección al lanzamiento antes de la edición: DateTime debe ser DateTime? .


Para aquellos que se encuentren con esto aquí es la respuesta más simple, me encontré con el mismo problema, pero no necesitaba DateTime. El XMLElement solo necesita un get no un set cuando se procesa XML.

private DateTime _fechaInicioRelacion; [XmlElement("FEC_INICIO_REL")] public string FechaInicioRelacionString { get { return _fechaInicioRelacion.ToString("yyyy-MM-ddTHH:mm:ss"); } set { } } [XmlIgnore] public DateTime FechaInicioRelacion { get { return _fechaInicioRelacion; } set { _fechaInicioRelacion = value; } }


Resolví el problema almacenando la fecha en una cadena y luego creando un getter que analiza la fecha y la devuelve como DateTime.

Código de muestra:

[XmlElement("Valid")] public string _Valid { get; set; } [XmlIgnore] public bool? Valid { get { if (!string.IsNullOrWhiteSpace(_Valid)) { return bool.Parse(_Valid); } return null; } }