欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET实现XML与DataTable互转的实例代码

程序员文章站 2024-03-04 16:45:41
复制代码 代码如下:private string convertdatatabletoxml(datatable xmlds)     {...

复制代码 代码如下:

private string convertdatatabletoxml(datatable xmlds)

    {

        memorystream stream = null;

        xmltextwriter writer = null;

        try

        {

            stream = new memorystream();

            writer = new xmltextwriter(stream, encoding.default);

            xmlds.writexml(writer);

            int count = (int)stream.length;

            byte[] arr = new byte[count];

            stream.seek(0, seekorigin.begin);

            stream.read(arr, 0, count);

            utf8encoding utf = new utf8encoding();

            return utf.getstring(arr).trim();

        }

        catch

        {

            return string.empty;

        }

        finally

        {

            if (writer != null) writer.close();

        }

    }

    private dataset convertxmltodataset(string xmldata)

    {

      stringreader stream = null;

      xmltextreader reader = null;

      try

      {

        dataset xmlds = new dataset();

        stream = new stringreader(xmldata);

        reader = new xmltextreader(stream);

        xmlds.readxml(reader);

        return xmlds;

      }

      catch (exception ex)

      {

        string strtest = ex.message;

        return null;

      }

      finally

      {

        if (reader != null)

        reader.close();

      }

    }