0

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.

  • [How to Deserialize XML document](https://stackoverflow.com/a/364401/14868118) I think this link is a solution you are looking for. – oktaykcr Apr 03 '21 at 15:29

1 Answers1

0

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;
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115