简体   繁体   中英

How to create a class to be serialized to have this output XML

<Root>
    <Apple Clr="RedViolet">1</Apple>
    <Apple Clr="RedOrange">3</Apple>

    <AppleGroup Clr="Red">
        <Apple Clr="LightRed">4</Apple>
        <Apple Clr="DarkRed">12</Apple>   
        <Apple Clr="MediumRed">10</Apple>
    </AppleGroup>
    <AppleGroup Clr="Red">
        <Apple Clr="LightRed">4</Apple>
        <Apple Clr="DarkRed">12</Apple>   
        <Apple Clr="MediumRed">10</Apple>
    </AppleGroup>
</Root>

I have serialized a class before but only for simple and straight-forward class serialization only. I don't have any idea in this :(

You need 3 seperate Classes First one for the whole XML:

[Serializable ()]
[XmlRoot ( "Root" )]
public class XmlRootClass{
    [XmlElement ( "Apple" )]
    public List<Apple> apples{
        get;
        set;
    }

    [XmlElement ( "AppleGroup " )]
    public List<AppleGroup> applegroups{
        get;
        set;
    }
}

second one for the Apple

[Serializable ()]
public class Apple{
    [XmlAttribute("Clr")]
    public string color{
        get;set;
    }

    [XmlText]
    public string Text{
        get;set;
    } 
}

and the third one for the Apple Group

[Serializable ()]
    public class AppleGroup{
    [XmlAttribute("Clr")]
    public string color{
        get;set;
    }

    [XmlElement ( "Apple" )]
    public List<Apple> apples{
        get;
        set;
    } 
}

You can use a Visual Studio feature to create a Serializable class from any Xml data. Firstly you have to copy the Xml data for which you want to create a class and then select Menu -> Paste Special -> Paste Xml As Classes

This is very handy and useful in some cases. I am not sure this will fulfill your demand in current case, but this may help you in future.

在此处输入图片说明

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