I have been working on the project recently. I want to record several data conversions for the problems encountered in the past few days.
1. datatable conversion to XML
Public static string datatabletoxml (this datatable DT) {// the first type of returned XML string is relatively clean. If the data in the datatable row is empty, it is not written to the XML string system. io. textwriter Tw = new system. io. stringwriter (); DT. writexml (TW); Return TW. tostring (); // The second is the same as the first memorystream MS = NULL; xmltextwriter xmlwt = NULL; MS = new memorystream (); /// xmlwt = new xmltextwriter (MS, encoding. unicode); // obtain the data DT in DS. 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 (); string returnvalue = ucode. getstring (temp ). trim (); Return returnvalue; // The XML string returned in the third type is complex, including the definition of each column in The datatable and the field type, including the row value of the datatable, and other attributes stringbuilder sb = new stringbuilder (); xmlwriter writer = xmlwriter. create (SB); xmlserializer serializer = new xmlserializer (typeof (datatable); serializer. serialize (writer, DT); writer. close (); return sb. tostring ();}
2. convert an XML string to a datatable
Public static dataset xmltodatatable (this string strdata) {If (! String. isnullorempty (strdata) {xmldocument xmldoc = new xmldocument (); dataset DS = new dataset (); try {xmldoc. loadxml (strdata); DS. readxml (getstream (xmldoc. outerxml); Return Ds;} catch (exception e) {Throw e ;}} else {return NULL ;}}
The getstream method is used as follows:
Public static streamreader getstream (this string xmlstr) {byte [] tempbyte = encoding. utf8.getbytes (xmlstr); memorystream stream = new memorystream (tempbyte); // stream. position = 0; streamreader = new streamreader (Stream); Return streamreader ;}
The above method only reads the XML string into dataset, and then finds the previously defined able in dataset.
A datatable is called to convert the data into an XML string.
Datatable dt = new datatable ("test"); string xmldata = DT. datatabletoxml ();
Convert XML strings to datatable
String xmldata = "here is an XML string"; datatable dt = xmldata. xmltodatatable (). Tables ["test"];
Currently, the custom extension method is used for both methods.
Above.