How to Xml serialize LinkedList?

.NET 2

Actually there are methods for XML serialization List<T>. What if I have an object that has a public member LinkedList<T>?

Without the creation of a duplicate public both List<T>from LinkedList<T>. Perhaps this is a way to control the serialization of Xml, such as binary (OnSerializing, OnDeserializing).

Can't XML serialize an object using an open element LinkedList<T>?

EDIT:

Test Example for Fix Using IXmlSerializable

using System.Xml.Serialization;

public class Foo : IXmlSerializable {        
    private int _Id;
    private string _Name;

    public string Name {
        get { return _Name; }
        set { _Name = value; }
    }        
    
    private int _Age;
    public string Age {
        get { return _Age; }
        set { _Age = value; }
    }
    
    private LinkedList<Bar> _linkedList = new LinkedList<Bar>();
    [XmlArray()]
    public List<Bar> MyLinkedList {
        get { return _linkedList; }
        set { _linkedList = value; }
    }
    
    public System.Xml.Schema.XmlSchema GetSchema() {
        return null;
    }
    
    public void ReadXml(System.Xml.XmlReader reader) {
        _Name = reader.ReadString(); // ? '            
        _Age = reader.ReadString(); // ? '
        // foreach MyLinkedList 
    }
    
    public void WriteXml(System.Xml.XmlWriter writer) {
        writer.WriteString(_Name); // ? '
        writer.WriteString(_Age); // ? '
        // foreach MyLinkedList 
    }
}
0
source share
1 answer

XmlSerializer IXmlSerializable List<T> LinkedList<T>. DataContractSerializer , , , .NET 2.0.


:

IXmlSerializable LinkedList<T>:

public class Foo : IXmlSerializable
{
    public LinkedList<int> List { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        throw new System.NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("List");
        foreach (var item in List)
        {
            writer.WriteElementString("Item", item.ToString());    
        }
        writer.WriteEndElement();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo
        {
            List = new LinkedList<int>(new[] { 1, 2, 3 })
        };
        var serializer = new XmlSerializer(foo.GetType());
        serializer.Serialize(Console.Out, foo);
    }
}

, , XmlSerializer.

+2

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


All Articles