Reputation: 11063
I'm trying to deserialize a xml string to a custom class, but I can get my "Riesgo" field filled with asegurado class:
<xml xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<CodPostal>28029</CodPostal>
<Canal>216 </Canal>
<FormaPago>M</FormaPago>
<ConSeguro>N</ConSeguro>
<FechaEfecto>01/01/2014</FechaEfecto>
<Riesgo>
<asegurado>
<sexo>H</sexo>
<edad>37</edad>
<parentesco>M</parentesco>
</asegurado>
<asegurado>
<sexo>M</sexo>
<edad>34</edad>
<parentesco>C</parentesco>
</asegurado>
<asegurado>
<sexo>H</sexo>
<edad>4</edad>
<parentesco>D</parentesco>
</asegurado>
</Riesgo>
</xml>
I have tried several things but the List inside Riesgo always come null.
public class TarificadorObject
{
[DataContract]
[Serializable]
[XmlRoot("xml")]
public class TarificadorIn
{
[XmlElement("CodPostal")]
public Int32 CodPostal { get; set; }
[XmlElement("Canal")]
public Int32 Canal { get; set; }
[XmlElement("Riesgo")]
[XmlArrayItem("asegurado", Type = typeof (Asegurado))]
public List<Asegurado> asegurado
{
get { return _asegurados; }
set { _asegurados = value; }
}
[XmlElement("FechaEfecto")]
public string FechaEfecto { get; set; }
private List<Asegurado> _asegurados = new List<Asegurado>();
}
[Serializable]
public class Asegurado
{
[XmlAttribute("sexo")]
public string sexo { get; set; }
[XmlAttribute("edad")]
public Int32 edad { get; set; }
[XmlAttribute("parentesco")]
public string parentesco { get; set; }
}
}
Upvotes: 3
Views: 511
Reputation: 1064204
You want:
[XmlArray("Riesgo")]
[XmlArrayItem("asegurado", Type = typeof (Asegurado))]
not XmlElementAttribute
(which causes the list contents to be placed directly under the parent).
Actually, you can be more frugal if you want; the Type
is implied (from the list) and can be omitted if you want.
Note also that these are wrong:
[XmlAttribute("sexo")]
public string sexo { get; set; }
[XmlAttribute("edad")]
public Int32 edad { get; set; }
[XmlAttribute("parentesco")]
public string parentesco { get; set; }
They are not xml attributes - they are elements; you can replace that with:
public string sexo { get; set; }
public int edad { get; set; }
public string parentesco { get; set; }
(the default behavior is an element named for the property)
Upvotes: 3