C # Implements a DataTable, dataset, and XML transformation from one to the other

Source: Internet
Author: User

/**////<summary>///convert DataSet, DataTable, DataView format to XML string, XML file///</summary> public class Datato XML {/**////<summary>//Convert DataTable object to XML string///</summary>//<param Name= "DT" >datatable objects </param>///<returns>xml strings </returns> public static string Cdatat                oXML (DataTable dt) {if (dt! = NULL) {MemoryStream ms = NULL;                XmlTextWriter XMLWT = null;                    try {ms = new MemoryStream ();                    Based on Ms instantiation XMLWT XMLWT = new XmlTextWriter (MS, Encoding.unicode); Gets the data in the DS dt.                    WRITEXML (XMLWT); int count = (int) Ms.                    Length;                    byte[] temp = new Byte[count]; Ms.                    Seek (0, Seekorigin.begin); Ms.                    Read (temp, 0, count);        Returns Unicode-encoded text            UnicodeEncoding ucode = new UnicodeEncoding (); String returnvalue = Ucode. GetString (temp).                    Trim ();                Return returnvalue;                } catch (System.Exception ex) {throw ex;                    } finally {//frees resource if (XMLWT! = null)                        {Xmlwt.close (); Ms.                        Close (); Ms.                    Dispose ();            }}} else {return ""; }} The conversion in some XML version of the problem, there will be Soaptoolkit call when the return value error, then this method can be used to do the conversion (it is recommended that everyone use the following method ...). Because I have been deeply affected by the method above ...         T_T).            public string Datatabletoxml (DataTable dt) {StringBuilder strxml = new StringBuilder ();            Strxml.appendline ("<XmlTable>"); for (int i = 0; i < dt. Rows.Count; i++) {                Strxml.appendline ("<rows>"); for (int j = 0; j < dt. Columns.count; J + +) {Strxml.appendline ("<" + dt. COLUMNS[J]. ColumnName + ">" + dt. ROWS[I][J] + "</" + dt. COLUMNS[J].                ColumnName + ">");            } strxml.appendline ("</rows>");            } strxml.appendline ("</XmlTable>");        return strxml.tostring ();  }/**////<summary>///Convert the table specified in the DataSet object to an XML string///</summary>//<param Name= "DS" >dataset object </param>///<param name= "Tableindex" >dataset object in the table index </param>//            /<returns>xml Strings </returns> public static string Cdatatoxml (DataSet ds, int tableindex) { if (tableindex! =-1) {return Cdatatoxml (ds.            Tables[tableindex]); } else {return Cdatatoxml (ds. Tables[0]); }}/**////<summary>//Convert DataSet object to XML string///</summary>//<param Name= "DS" >dataset objects </param>///<returns>xml strings </returns> public static string Cdatatox        ML (DataSet ds) {return Cdatatoxml (ds,-1); }/**////<summary>///Convert DataView object to XML string///</summary>//<param name= "DV ">dataview object </param>//<returns>xml string </returns> public static strings Cdatatoxml (Data View dv) {return Cdatatoxml (DV.        Table); }/**////<summary>//Save DataSet Object data as an XML file///</summary>//<param name= "DT ">DataSet</param>//<param name=" xmlfilepath ">xml file path </param>//<returns>bool Value </returns> public static bool Cdatatoxmlfile (DataTable DT, string xmlfilepath) {if (dt! = null) && (!string.                IsNullOrEmpty (Xmlfilepath)) {String path = HttpContext.Current.Server.MapPath (Xmlfilepath);                MemoryStream ms = NULL;                XmlTextWriter XMLWT = null;                    try {ms = new MemoryStream ();                    Based on Ms instantiation XMLWT XMLWT = new XmlTextWriter (MS, Encoding.unicode); Gets the data in the DS dt.                    WRITEXML (XMLWT); int count = (int) Ms.                    Length;                    byte[] temp = new Byte[count]; Ms.                    Seek (0, Seekorigin.begin); Ms.                    Read (temp, 0, count);                    Returns the Unicode encoded text unicodeencoding ucode = new UnicodeEncoding ();                    Write file StreamWriter sw = new StreamWriter (path); Sw.                    WriteLine ("<?xml version=" 1.0 "encoding=" Utf-8 "?>"); Sw. WriteLine (Ucode. GetString (temp). Trim ()); Sw.                    Close ();                return true;                } catch (System.Exception ex) {throw ex;                    } finally {//frees resource if (XMLWT! = null)                        {Xmlwt.close (); Ms.                        Close (); Ms.                    Dispose ();            }}} else {return false; }}/**////<summary>///Convert the table specified in the DataSet object to an XML file////</summary>//&L        T;param name= "DS" >dataset objects </param>///<param name= "Tableindex" >dataset objects in the table index </param> <param name= "Xmlfilepath" >xml file path </param>///<returns>bool] Value </returns> Pub  LIC static bool Cdatatoxmlfile (DataSet ds, int tableindex, string xmlfilepath) {          if (tableindex! =-1) {return Cdatatoxmlfile (ds.            Tables[tableindex], Xmlfilepath); } else {return Cdatatoxmlfile (ds.            Tables[0], Xmlfilepath); }}/**////<summary>//Convert DataSet object to XML File///</summary>//<param N Ame= "DS" >dataset object </param>///<param name= "xmlfilepath" >xml file path </param>//<return S>bool] Value </returns> public static bool Cdatatoxmlfile (DataSet ds, String xmlfilepath) {R        Eturn Cdatatoxmlfile (DS,-1, Xmlfilepath); }/**////<summary>//Convert DataView object to XML File///</summary>//<param name= "DV" >dataview Object </param>//<param name= "xmlfilepath" >xml file path </param>//<returns>bo OL] Value </returns> public static bool Cdatatoxmlfile (DataView DV, string xmlfilepath) {            Return Cdatatoxmlfile (DV.        Table, Xmlfilepath); }}/**////<summary>////XML-form string, XML criticizes converted to DataSet, DataTable Format///</summary> public class Xmltoda TA {/**////<summary>///Convert XML content string to DataSet object///</summary>//<param N Ame= "Xmlstr" >xml content strings </param>///<returns>dataset objects </returns> public static DataSet CX Mltodataset (String xmlstr) {if (!string.                IsNullOrEmpty (XMLSTR)) {StringReader strstream = null;                XmlTextReader xmlrdr = null;                    try {DataSet ds = new DataSet ();                    Read the information in the string strstream = new StringReader (XMLSTR);                    Get data in Strstream Xmlrdr = new XmlTextReader (Strstream); DS Gets the data ds in the Xmlrdr.                    READXML (XMLRDR); Return DS;                } catch (Exception e) {throw e;                    } finally {//frees resource if (xmlrdr! = null)                        {Xmlrdr.close ();                        Strstream.close ();                    Strstream.dispose ();            }}}} else {return null; }}/**////<summary>//Convert XML string to DataTable Object////</summary>//<para M name= "Xmlstr" >xml string </param>///<param name= "tableindex" >table table index </param>//<re        Turns>datatable object </returns> public static DataTable cxmltodatattable (string xmlstr, int tableindex) {return Cxmltodataset (XMLSTR).        Tables[tableindex]; }/**////<summary>//Convert XML string to DataTable object///lt;/summary>//<param name= "Xmlstr" >xml strings </param>///<returns>datatable objects </retur ns> public static DataTable cxmltodatattable (string xmlstr) {return Cxmltodataset (XMLSTR).        Tables[0];         }/**////<summary>///Read XML file information and convert to DataSet object///</summary>//<remarks>        DataSet ds = new DataSet ();        ds = Cxmlfiletodataset ("/xml/upload.xml"); </remarks>//<param name= "Xmlfilepath" >xml file address </param>//<returns>dataset Object & lt;/returns> public static DataSet Cxmlfiletodataset (string xmlfilepath) {if (!string.                IsNullOrEmpty (Xmlfilepath)) {String path = HttpContext.Current.Server.MapPath (Xmlfilepath);                StringReader strstream = null;                XmlTextReader xmlrdr = null; try {XmlDocument Xmldoc = new XmlDocument (); Loads the XML file xmldoc according to the address.                    Load (path);                    DataSet ds = new DataSet (); Reads a stream of characters from a file Strstream = new StringReader (xmldoc.                    INNERXML);                    Get data in Strstream Xmlrdr = new XmlTextReader (Strstream); DS Gets the data ds in the Xmlrdr.                    READXML (XMLRDR);                return DS;                } catch (Exception e) {throw e;                    } finally {//frees resource if (xmlrdr! = null)                        {Xmlrdr.close ();                        Strstream.close ();                    Strstream.dispose ();            }}}} else {return null; }}/**////<summary>///Read XML file information and convert to DataTable object        </summary>//<param name= "Xmlfilepath" >xml criticizes path </param>//<param name= "t Ableindex ">table index </param>///<returns>datatable object </returns> public static DataTable C Xmltodatatable (string xmlfilepath, int tableindex) {return Cxmlfiletodataset (Xmlfilepath).        Tables[tableindex]; }/**////<summary>///Read XML file information and convert to DataTable object///</summary>//<param Nam E= "Xmlfilepath" >xml criticizes path </param>//\ <returns>datatable Object </returns> public static Datata Ble cxmltodatatable (string xmlfilepath) {return Cxmlfiletodataset (Xmlfilepath).        Tables[0]; }    }

 

Using system;using system.data;using system.io;using system.xml;using system.text;//corresponding C # code: 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 (); }}

C # Implements a DataTable, dataset, and XML transformation from one to the other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.