Linq.Table serialization for XML

I have a very simple application that currently has one Linq to Sql class based on one table.

I need to serialize (in XML) all rows in a table using a DataContext for the Linq To Sql class.

How can I do it?

This is my current code:

    var db = new MyEntityDataContext();
    Stream fs = new FileStream("Output.xml", FileMode.Create);
    XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode);            

    serializer = new XmlSerializer(typeof(MyEntity));
    foreach (var row in db.MyEntitys)
    {
        // Serialize object to XML
        serializer.Serialize(writer,row);
    }

    writer.Close();

However, this excludes the following:  "Token StartElement in state Epilog would result in an invalid XML document."

I also tried:

XmlSerializer serializer2 = new XmlSerializer(db.MyEntitys.GetType());

but that throws an "To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy." exception.

+3
source share
1 answer

XmlSerializermay not be great with associations. If you enable serialization on the surface of the data context, it adds (WCF) attributes to the contract data. Maybe just use:

var data = db.MyEntitys.ToList();
var ser = new DataContractSerializer(data.GetType());
ser.WriteObject(dest, data);
+2
source

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


All Articles