簡體   English   中英

使用List <>將Xml字符串反序列化為對象

[英]Deserializing Xml string into object with List<>

我正在嘗試將xml字符串反序列化為自定義類,但我可以將我的“Riesgo”字段填充為asegurado類:

<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>

我嘗試了幾件事,但Riesgo里面的List總是無效。

 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; }
        }
    }

你要:

[XmlArray("Riesgo")]
[XmlArrayItem("asegurado", Type = typeof (Asegurado))]

不是XmlElementAttribute (導致列表內容直接放在父級下面)。

實際上,如果你願意,你可以更節儉; Type是隱含的(從列表中),如果需要可以省略。

還要注意這些是錯誤的:

[XmlAttribute("sexo")]
public string sexo { get; set; }
[XmlAttribute("edad")]
public Int32 edad { get; set; }
[XmlAttribute("parentesco")]
public string parentesco { get; set; }

它們不是xml屬性 - 它們是元素; 你可以用以下代替:

public string sexo { get; set; }
public int edad { get; set; }
public string parentesco { get; set; }

(默認行為是為屬性命名的元素)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM