简体   繁体   中英

XML serialization - complex type to c# class

I serialize XML files to objects. Let's not talk about how I serialize it as it's not the problem. The problem is how to build a class for complex type elements. For normal XML elements, I do it follows (using System.Xml.Serialization of course)

public class Item
{
    [XmlElement("thumbnail")]
    public string thumbnail { get; set; }
}

All works good. But for a complex type, I don't know how to represent it in a class, I tried to represent it by an array like this

public class Item
{
    [XmlArray("thumbnail")]

    [XmlArrayItem("url")]
    public string url { get; set; }

    [XmlArrayItem("width")]
    public string width { get; set; }

    [XmlArrayItem("height")]
    public string height { get; set; }

    public string[] thumbnail { get; set; }
 }

but this didn't work.

any ideas how to represent an XML complex element in a C# class?

You should have an Item class, and a Thumbnail class, more like this:

public class item {
    [XmlElement("thumbnail")]
    public thumbnail thumbnail {get;set;}
}

public class thumbnail
{
    [XmlElement("url")]
    public string url { get; set; }

    [XmlElement("width")]
    public string width { get; set; }

    [XmlElement("height")]
    public string height { get; set; }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM