简体   繁体   中英

Deserializing XML Array in unity

Im trying to deserialize an array of objects from a XML Document. The document built in the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <element>
      .....
   </element>
  <element>
      .....
   </element>
</root>

But for some reason Im having lots of problems doing so. This is my function which I call to deserialize it:

public static CardModel[] Load(string text)
        {
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "root";
            xRoot.IsNullable = true;
            
            XmlSerializer serializer = new XmlSerializer(typeof(CardModel[]),xRoot);
            StringReader reader = new StringReader(text);
            CardModel[] o = serializer.Deserialize(reader) as CardModel[];
            reader.Close();
            
            return o;
        }

And I am not sure if its done correctly or not. Because I know that in json you are unable to deserialize an array and you have to do some sort of "hack".

In the CardModel class (which is the element of the array) i use above the class the tag [XmlRoot("root")]. I have also tried to use [XmlRoot("element")] but still im getting stuck.

Afaik you can't directly deserialize into an array but would need a wrapper class like

[Serializable]
[XMLRoot("root")]
public class Root
{
    // This does the magic of treating all "element" items nested under the root
    // As part of this array
    [XmlArray("element")]
    public CardModel[] models;
}

And rather deserilialize into that like

public static CardModel[] Load(string text)
{  
    // I don't think that you need the attribute overwrite here
   
    var serializer = new XmlSerializer(typeof(Root));
    using(var reader = new StringReader(text))
    {
        var root = (Root) serializer.Deserialize(reader);
        return root.models;
    }
}

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