简体   繁体   中英

How to serialize a class with one of its members holding instance of another class

I have a class as below:

public class ItemGroup
{
    public int type;
    public Item[] item;
}

public class Item
{
    public string name;
    public int category;
}

I would like to convert ItemGroup into an XML like this

<ItemGroup>
    <type>1</type>
    <Item>
        <name>HELLO</name>
        <category>1</category>
    </Item>
    <Item>
        <name>WORLD</name>
        <category>2</category>
    </Item>
</ItemGroup>

What XML Tag need to used to specified in the class? I am using C#

Perhaps counter-intuitively, you only need to use the XmlElement attribute. This instructs the XmlSerializer to build the Item sets one-by-one after each other which will match the spec you provided. In addition, you need to specify the element name explicitly since your field is lower case "item", but you want to have upper case "Item".

public class ItemGroup
{
    public int type;

    [XmlElement("Item")]
    public Item[] item;
}

public class Item
{
    public string name;
    public int category;
}

I would recommend you to not create the xml manually, but serialize the class using this simple code:

     XmlSerializer mySerializer = new XmlSerializer(objectToSerialize.GetType());
     StreamWriter myWriter = new StreamWriter(myxml.xml);
     mySerializer.Serialize(myWriter, objectToSerialize);
     myWriter.Close();

In some cases you should apply SerializableAttribute to your class.

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