简体   繁体   English

如何在C#中将DataTable转换为XML文件?

[英]How can I convert a DataTable to an XML file in C#?

I want to convert a DataTable to an XML file in C#. 我想将DataTable转换为C#中的XML文件。 How can I do this? 我怎样才能做到这一点?

You can use DataTable.WriteXml Method. 您可以使用DataTable.WriteXml方法。

Here is an example; 这是一个例子;

How can i convert my datatable into XML using C# 2.0? 如何使用C#2.0将数据表转换为XML?

string result;
using (StringWriter sw = new StringWriter()) {
dataTable.WriteXml(sw);
result = sw.ToString();
}

If you don't actually need a string but read-only, processable XML, it's a better idea to use MemoryStream and XPathDocument: 如果您实际上不需要字符串,而是只读的,可处理的XML,则最好使用MemoryStream和XPathDocument:

XPathDocument result;
using (MemoryStream ms = new MemoryStream()) {
dataTable.WriteXml(ms);
ms.Position = 0;
result = new XPathDocument(ms);
}

You can use the writeXML method to save it as XML ( Source ). 您可以使用writeXML方法将其另存为XML( Source )。

You can also use serialization/desirialization as described in the fifth post of this forum . 您还可以按照本论坛第五篇文章中的描述使用序列化/反序列化。

Another way to get this done is by adding the data table to dataset and calling the GetXml() on the dataset.In addition to this dataset is equipped with the WriteXml() and ReadXml() for writing/reading the XML directly to/from a file path or stream. 完成此操作的另一种方法是将数据表添加到数据集并在数据集上调用GetXml() 。此外,该数据集还配备了WriteXml()ReadXml() ,可直接将XML写入/从中读取XML。文件路径或流。

DataSet ds = new DataSet();
ds.Tables.Add(dt1); // Table 1
ds.Tables.Add(dt2); // Table 2...
...
string dsXml= ds.GetXml();
...
using (StreamWriter fs = new StreamWriter(xmlFile)) // XML File Path
{
      ds.WriteXml(fs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM