tags:

views:

448

answers:

1

Hi,

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

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

How do I go about doing this?

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 it throws the following exception: "Token StartElement in state Epilog would result in an invalid XML document."

I have also tried:

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

but this throws a "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.

A: 

XmlSerializer may not be wonderful with associations. If you enable serialization on the data-context surface, it adds (WCF) data-contract attributes. Perhaps just use:

var data = db.MyEntitys.ToList();
var ser = new DataContractSerializer(data.GetType());
ser.WriteObject(dest, data);
Marc Gravell
Using ToList() on the Linq.Table did the trick and it now works using DataContractSerializer or XmlSerializer. Should have tried that myself. Thanks.Is there a straight forward way to adjust element names in the resulting Xml file, particularly the <ArrayOfMyEntity> root element?
TonE
I confess, I haven't had cause to try... so I don't know. With XmlSerializer, maybe one of the overloads that accepts the attribute definitions?
Marc Gravell
Yep, it can be specified with'XmlSerializer(Type type, XmlRootAttribute root);'Thanks again for your help.
TonE