Search code examples
c#xmlunity-game-enginexml-serializationmonodevelop

XML Serialization in Unity - Have an array hold different arrayitems?


So I'm working on my game in Unity, and I encountered a problem regarding XML. I've setup a system thanks to a tutorial that allows me to create items by reading their data from an XML database. But there is one problem. I want to set up my XML file to be read as follows:

        <resistance>
            <physical>
                <phy>60.0</phy>
            </physical>

            <air>
                <air>50.0</air>
            </air>
        </resistance>

However, I have not found a way to set the as the root to check the data in.

The format of the XML file is as follows:

    <Item>
        <id>0</id>
        <name>Helmet</name>
        <resistance>
            <physical>
                <phy>60.0</phy>
            </physical>

            <air>
                <air>50.5</air>
            </air>
        </resistance>
    </Item>

[XmlArray("resistance"), XmlArrayItem("physical")] only reads the part. I've also tried writing everything as follows:

[XmlArray("resistance"), XmlArrayItem("physical"), XmlArrayItem("phy")]
public float[] phyres;
[XmlArray("air"), XmlArrayItem("air")]
public float[] airres;

But the XML file then got messy, although the data was read and I got the correct resistances, what followed after was not read, as if resistance became the new permament root of the XML file. Thank you in advance.

Edit: In other words, I want to have a subroot in my the child, and hold a few different arrays there.

Edit:Edit: Thank you jdweng, this ended up more simple to write:

[XmlElement("resistance"), XmlArrayItem("physical")]
public float[] phyres;
[XmlElement("air")]
public float[] airres;

But I still get the same issue. The root/namespace is set to , and everything is read from that namespace afterwards. Not even the after affects it.


Solution

  • As I read it, your requirement is a resistance element that contains an a physical and an air element. This:

    [XmlElement("resistance"), XmlArrayItem("physical")]
    public float[] phyres;
    [XmlElement("air")]
    public float[] airers;
    

    Doesn't represent that. It implies a resistance element containing multiple physical elements followed by an air element.

    Here is a class structure that mirrors your XML:

    public class Item
    {
        [XmlElement("id")]
        public int Id { get; set; }
    
        [XmlElement("name")]
        public string Name { get; set; }
    
        [XmlElement("resistance")]
        public Resistance Resistance { get; set; }
    }
    
    public class Resistance
    {
        [XmlArray("physical")]
        [XmlArrayItem("phy")]
        public float[] Phyres { get; set; }
    
        [XmlArray("air")]
        [XmlArrayItem("air")]
        public float[] Air { get; set; }
    }