将 DataTable 行集合反序列化为 List
我有一个包含数据行的数据表。我有一个类,其属性与行列名称匹配。
如何获得一个由 DataTable 行信息填充的列表?
我是否调用类似 (MyType)new XmlSerializer(typeof(MyType)).Deserialize(new XMLReader(Table.WriteXML())); 的内容?
I have a DataTable with rows of data. I have a class with properties that match the row column names.
How can I have a List that is populated from the DataTable Row information?
Do I call something like (MyType)new XmlSerializer(typeof(MyType)).Deserialize(new XMLReader(Table.WriteXML()));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议编写类来执行此转换,而不是使用 XML 序列化,后者需要大量额外工作并将对象与数据模型联系得太紧密。
另一方面,有时您只需从 XML 反序列化集合。要实现此目的,您需要做的就是告诉
XmlSerializer
将哪个节点映射到集合。默认情况下,
DataTable.WriteXml
创建一个名为
的根元素。例如,如果您从名为“Name”的DataTable
进行写入,其中包含“FirstName”和“LastName”列,您将得到以下结果:问题是
XmlSerializer
不知道“DocumentElement”应该反序列化到您的集合类。有两种方法可以告诉它如何进行。按照约定,
XmlSerializer
知道名为“ArrayOfMyClass”的根元素应映射到MyClass
的集合。将您的
DataTable
添加到名为“ArrayOfMyClass”的DataSet
中,像这样序列化它......它反序列化为
List
> 根据需要。手动
作为替代方案,您可以这样做:
假设其他一切都正常(即您的数据行列名称与您的类的属性名称匹配),这将按预期反序列化到您的
List< /代码>。
编辑:请注意,这种方法有一个相当严重的问题(有一个相当麻烦的解决方法),在此问题中描述: XmlSerializer 性能问题。
I recommend writing classes to perform this transformation instead of using XML serialization, which requires a lot of extra work and ties your objects too closely to your data model.
On the other hand, sometimes you just have to deserialize collections from XML. To accomplish this, all you need to do is tell the
XmlSerializer
which node to map to the collection.By default,
DataTable.WriteXml
creates a root element called<DocumentElement>
. For example, if you write from aDataTable
called "Name" that has "FirstName" and "LastName" columns, you'll get this:The problem is that the
XmlSerializer
doesn't know that "DocumentElement" should be deserialized to your collection class. There are two ways to tell it how.By Convention
The
XmlSerializer
knows that a root element named "ArrayOfMyClass" should map to collections ofMyClass
.Add your
DataTable
to aDataSet
named "ArrayOfMyClass" to serialize it like this ....... which deserializes into a
List<MyClass>
as desired.By Hand
As an alternative, you can do it like this:
Presuming everything else is ok (that is, your data row column names match your class' property names), this will deserialize as expected into your
List<MyClass>
.Edit: note that this approach has a rather severe problem (with a moderately cumbersome workaround) described in this SO question: XmlSerializer Performance Issue.
如果我正确理解你的问题,你想将每行数据的字段放入 YourClass 的实例中,然后将实例存储在 List 中?
在这种情况下,最直接的方法就是
If I understand your question correctly, you want to put the fields of each row of data into instances of YourClass and then store the instances in a List?
In that case, the most straightforward way is to