The postgraduate entrance exam results are helpless. We had to wait for the national line. I have recently obtained a job. for work reasons, I need to convert a table in a database into XML. originally, SQL Server 2000 and later have the for XML function that can be used directly, but you have no choice but to writeCode. So I wrote one by myself. Below are several major functions, and the overall code will be sent to my download. Free Download.
/// <Summary> <br/> // read a datatable from a SQL database and translate to XML format. <br/> // </Summary> <br/> private void sqldatatoxmlfile (string path) <br/>{< br/> string connectstring = string. format (@ "Data Source = {0}; user id = {1}; Password = {2}; database = {3}; Connect timeout = 10000;", @ textinstance. text, textusername. text, textpwd. text, textdb. text); <br/> string sqlcommandtext = string. forma T (@ "select * from {0}", texttablename. text); <br/> sqlconnection = new sqlconnection (connectstring); <br/> sqldataadapter sdataadapter = new sqldataadapter (sqlcommandtext, sqlconnection ); <br/> datatable dt = new datatable (); <br/> sdataadapter. fill (DT); <br/> createxml (ableabletoxml (DT), PATH ); <br/>}< br/> /// <summary> <br/> // read a DB table from database and translate to XML And return. <br/> // </Summary> <br/> // <returns> </returns> <br/> private string datatabletoxml (datatable DT) <br/>{< br/> stringbuilder sb = new stringbuilder (); <br/> Sb. appendline ("<root>"); <br/> for (INT I = 0; I <DT. rows. count; I ++) <br/>{< br/> Sb. appendline ("<rows>"); <br/> for (Int J = 0; j <DT. columns. count; j ++) <br/>{< br/> Sb. appendline ("<" + dt. columns [J]. columnname + ">" + dt. row S [I] [J]. tostring () + "</" + dt. columns [J]. columnname + ">"); <br/>}< br/> Sb. appendline ("<rows>"); <br/>}< br/> Sb. appendline ("</root>"); <br/> return sb. tostring (); <br/>}< br/> /// <summary> <br/> // write a XML file to a specfic path <br/> /// </Summary> <br/> // <Param name = "content"> </param> <br/> // <Param name = "path"> </param> <br/> private void createxml (string content, string path) <br/> {<Br/> streamwriter Sw = new streamwriter (PATH); <br/> Sw. writeline ("<? XML version =/"1.0/" encoding =/"UTF-8/"?> "); <Br/> Sw. writeline (content); <br/> Sw. Close (); <br/> Sw. Dispose (); <br/>}
The following is a tool diagram: