[英]How to write xml file from IDataReader in C#
If I have an IDataReader, how would i go about constructing a xml writer to output to xml. 如果我有一个IDataReader,我将如何构造一个XML编写器以输出到xml。 Would It require a custom stream or writer? 是否需要自定义流或编写器? I'm trying to write to an xml file but I have access to an IDataReader. 我正在尝试写入xml文件,但可以访问IDataReader。
One approach would be to build a class that mimics the data in the IDataReader
and simply serialize it to XML. 一种方法是建立一个类,该类模仿IDataReader
的数据并将其简单地序列化为XML。 Let's say the data in the data reader was Field1, Field2, Field3
, the class would look like this: 假设数据读取器中的数据是Field1, Field2, Field3
,则该类如下所示:
public class Data
{
public string Field1;
public string Field2;
public string Field3;
}
Of course the data types could differ. 当然,数据类型可以不同。 Now, all we need to do is read the data into the class, that might look something like this: 现在,我们要做的就是将数据读入类,看起来可能像这样:
var list = new List<Data>();
while (reader.Read())
{
var o = new Data();
o.Field1 = reader["Field1"];
o.Field2 = reader["Field2"];
o.Field3 = reader["Field3"];
list.Add(o);
}
var serializer = new XmlSerializer(typeof(List<Data>));
using (TextWriter textWriter = new StreamWriter(fileName))
{
serializer.Serialize(textWriter, list);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.