C # xml serializer - serialize derived objects

I want to serialize the following:

[Serializable]
[DefaultPropertyAttribute("Name")]
[XmlInclude(typeof(ItemInfo))]
[XmlInclude(typeof(ItemInfoA))]
[XmlInclude(typeof(ItemInfoB))] 
public class ItemInfo
{
    public string name;

    [XmlArray("Items"), XmlArrayItem(typeof(ItemInfo))]
    public ArrayList arr;

    public ItemInfo parentItemInfo;
}

[Serializable]
[XmlInclude(typeof(ItemInfo))]
[XmlInclude(typeof(ItemInfoA))]
[XmlInclude(typeof(ItemInfoB))] 
public class ItemInfoA : ItemInfo
{
...
}

[Serializable]
[XmlInclude(typeof(ItemInfo))]
[XmlInclude(typeof(ItemInfoA))]
[XmlInclude(typeof(ItemInfoB))] 
public class ItemInfoB : ItemInfo
{
...
}

The class itemInfodescribes a container that may contain other itemInfoobjects in the list of arrays, parentItemInfodescribes which is the parent container of product information.

Since ItemInfoAand ItemInfoBare derived from itemInfo, they can also be members of the array list and parentItemInfo, therefore, when you try to serialize these objects (which may contain a lot of objects in the hierarchy), it fails with an exception

IvvalidOperationException.`there was an error generating the xml file `

My question is:

What attributes do I need to add to the class itemInfoso that it is serializable?

Note: an exception occurs only when ItemInfo [A] / [B] is initialized with parentItemInfoor arrayList.

Help me please!

Thank!

+3
1

, , . , XmlSerializer , graph, . :

[XmlIgnore]
public ItemInfo parentItemInfo;

, , , .

- InnerException - , , , , (catch ex):

while(ex != null) {
    Debug.WriteLine(ex.Message);
    ex = ex.InnerException;
}

, :

" ItemInfoA."


, , ( , ArrayList, ) - ; , :

[DefaultPropertyAttribute("Name")]
[XmlInclude(typeof(ItemInfoA))]
[XmlInclude(typeof(ItemInfoB))] 
public class ItemInfo
{
    [XmlElement("name")]
    public string Name { get; set; }

    private readonly List<ItemInfo> items = new List<ItemInfo>();
    public List<ItemInfo> Items { get { return items; } }

    [XmlIgnore]
    public ItemInfo ParentItemInfo { get; set; }
}
public class ItemInfoA : ItemInfo
{
}
public class ItemInfoB : ItemInfo
{
}

( ) ( ; bredth-first Stack<T> Queue<T>; ):

public static void SetParentsRecursive(Item parent)
{
    List<Item> done = new List<Item>();
    Stack<Item> pending = new Stack<Item>();
    pending.Push(parent);
    while(pending.Count > 0)
    {
        parent = pending.Pop();
        foreach(var child in parent.Items)
        {
            if(!done.Contains(child))
            {
                child.Parent = parent;
                done.Add(child);
                pending.Push(child);
            }                
        }
    }
}
+8

Source: https://habr.com/ru/post/1789173/


All Articles