LinkedList <T> cannot be serialized using XMLSerializer

LinkedList link cannot be serialized using XmlSerializer.

Now, how to save / retrieve data from a serialized LinkedList object. Should I do custom serialization?

What I tried to do:

using System.Xml.Serialization;

[Serializable()]
public class TestClass
{
    private int _Id;
    private string _Name;
    private int _Age;
    private LinkedList<int> _linkedList = new LinkedList<int>();

    public string Name {
        get { return _Name; }
        set { _Name = value; }
    }
    
    public string Age {
        get { return _Age; }
        set { _Age = value; }
    }
    
    [XmlArray()]
    public List<int> MyLinkedList {
        get { return new List<int>(_linkedList); }
        set { _linkedList = new LinkedList<int>(value); }
    }
}

What I got (name, age and some items in mylinkedlist):

<?xml version="1.0"?>
<TestClass 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>testName</Name>
  <Age>10</Age>
  <MyLinkedList />
</TestClass>

So, the items in the linked list were not serialized ... :(

0
source share
1 answer

One possibility would be to create a serializable collection containing the same objects as the linked list. For instance. (Unverified):

LinkedList<Foo> ll = PopulateLinkedList();
List<Foo> list = new List<Foo>(ll);

list. , Foo , , / b/c, List<T> . , LinkedList<T>, , , , .


, , . VS2008, , - - , .

:

[Serializable]
public class MyClass
{
    private string name;
    private int age;
    private LinkedList<int> linkedList = new LinkedList<int>();

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    [XmlArray]
    public List<int> MyLinkedList
    {
        get { return new List<int>(linkedList); }
        set { linkedList = new LinkedList<int>(value); }
    }
}

:

class Program
{
    static void Main(string[] args)
    {
        MyClass c = new MyClass();

        c.Age = 42;
        c.Name = "MyName";
        c.MyLinkedList = new List<int>() { 1, 4, 9 }; // Your property impl requires this be set all at once, not one element at a time via the property.

        XmlSerializer s = new XmlSerializer(typeof(MyClass));
        StringWriter outStream = new StringWriter();
        s.Serialize(outStream, c);

        Console.Write(outStream.ToString());

        return;
    }
}

:

<?xml version="1.0" encoding="utf-16"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>MyName</Name>
  <Age>42</Age>
  <MyLinkedList>
    <int>1</int>
    <int>4</int>
    <int>9</int>
  </MyLinkedList>
</MyClass>
+4

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


All Articles