Serilializing Linq.Table到XMLLinq、Serilializing、XML、Table

2023-09-05 02:45:27 作者:同归

我有一个非常简单的应用程序,它目前有一个单一的LINQ到SQL类基于一个表。

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

我需要序列化(以XML)的所有行中使用的DataContext的LINQ to SQL的类表。

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

我如何去这样做?

这是我目前的code:

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();

然而,它抛出以下异常:  令牌的StartElement状态结语将导致一个无效的XML文档中,

However it throws the following exception: "Token StartElement in state Epilog would result in an invalid XML document."

我也曾尝试:

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

不过,这将引发一个 要XML序列化,而自IEnumerable继承的类型必须有加(System.Object的)各级的继承层次结构的实现。 例外。

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.

推荐答案

的XmlSerializer 可能不精彩与关联。如果启用序列化的数据上下文的表面,它增加(WCF)数据契约属性。也许只需使用:

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);