C # Error - XML Serialization

0

I encountered this error when trying to load an XML file through three scripts: one called Item, another ItemCollection, and the script to load the XML file.

Item:

using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

public class Item : MonoBehaviour {


[XmlAttribute("id")]
public string id;

[XmlAttribute("Nome")]
public string Nome;

[XmlAttribute("Preco")]
public float Preco;
}

ItemCollection

using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
using System.IO;


[XmlRoot("DataBase")]
public class ItemCollection : MonoBehaviour {
    [XmlArray("Produtos")]
    [XmlArrayItem("Produto")]
    public List<Item> Produtos = new List<Item>();

    public static ItemCollection Load(string path)
    {
        TextAsset _xml_ = Resources.Load <TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));

        StringReader reader = new StringReader(_xml_.text);

        ItemCollection Produtos = serializer.Deserialize(reader) as ItemCollection;

        reader.Close();

        return Produtos;
    }
}

Loader:

using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;

public class LoadXml : MonoBehaviour {

    public const string path = "Nomes_E_Precos";

    void Start () {
        ItemCollection itemCollection = ItemCollection.Load(path);

        foreach (Item Produto in itemCollection.Produtos)
        {
            Debug.Log(Produto.Nome + Produto.id + Produto.Preco);
        }
    }


}

However, give me the error (in the engine) in the title:

  To be XML serializable, types which inherit from IEnumerable must have an implementation of Add (System.Object)

Any solution?

    
asked by anonymous 09.07.2017 / 17:19

1 answer

0

What is happening is that XmlSerializer expects a class that is inherited from IEnumerable , that is, that stores and handles collections of items. The list ( List ), for example, is one of them, but its ItemCollection class (which you are actually trying to serialize) is not!

The error indicates that your class does not have the method Add , just because it is in the interface IEnumerable .

One possible solution is for you to try (to) directly serialize the Produtos :

public static List<Item> Load(string path)
{
    TextAsset _xml_ = Resources.Load <TextAsset>(path);

    XmlSerializer serializer = new XmlSerializer(typeof(List<Item>));

    StringReader reader = new StringReader(_xml_.text);

    List<Item> Produtos = serializer.Deserialize(reader) as List<Item>;

    reader.Close();

    return Produtos;
}
    
26.08.2017 / 16:14