反序列化XML数组

时间:2017-09-18 18:43:31

标签: c# xml-serialization xml-deserialization

我使用单个元素进行反序列化。但是,当我有xml元素数组时,我的代码无效

以下是我的代码。

XML:

<data>
    <cars>
        <body>
            <color>blue<color>
            <type>sedan</type>
        </body>
        <details>
            <year>2016</year>
            <make>Infiniti</make>
        </details>
    </cars>
    <cars>
        <body>
            <color>white<color>
            <type>SUV</type>
        </body>
        <details>
            <year>2016</year>
            <make>Lexus</make>
        </details>
    </cars>
</data>

DTO

[XmlRoot("cars")]
public class CarDetails
{
        [XmlElement("body")]
        public Body BodyList { get; set; }

        [XmlElement("details")]
        public DetailsList details { get; set; }
}

public class Body
        {
            public string Color { get; set; }
            public string Type { get; set; }
        }

public class DetailsList
        {
            public int Year { get; set; }
            public string Make { get; set; }
        }

以下是反序列化的代码:

CarDetails[] details;
XmlSerializer serializer = new XmlSerializer(typeof(CarDetails[]));
            using (TextReader reader = new StringReader(output))
            {
                details= (CarDetails[])serializer.Deserialize(reader);
            }

请帮我解决如何反序列化XML数组

1 个答案:

答案 0 :(得分:0)

首先,您的XML无效。

<color>blue<color>
你忘了在这里关闭颜色了。 其次,最好不要自己做。最好使用一些工具。像online XML to C# generator一样。你可以找到类似的JSON。在我的情况下,它给出了这个结果(看看Data类):

[XmlRoot(ElementName="body")]
public class Body {
    [XmlElement(ElementName="color")]
    public string Color { get; set; }
    [XmlElement(ElementName="type")]
    public string Type { get; set; }
}

[XmlRoot(ElementName="details")]
public class Details {
    [XmlElement(ElementName="year")]
    public string Year { get; set; }
    [XmlElement(ElementName="make")]
    public string Make { get; set; }
}

[XmlRoot(ElementName="cars")]
public class Cars {
    [XmlElement(ElementName="body")]
    public Body Body { get; set; }
    [XmlElement(ElementName="details")]
    public Details Details { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="cars")]
    public List<Cars> Cars { get; set; }
}