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

前端 未结 3 1046
南笙
南笙 2020-11-30 08:14

I want to convert a DataTable to an XML file in C#. How can I do this?

3条回答
  •  暖寄归人
    2020-11-30 08:44

    You can use DataTable.WriteXml Method.

    Here is an example;

    How can i convert my datatable into XML using C# 2.0?

    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:

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

提交回复
热议问题