Key Code :
Private Void Btnsearch_click ( Object Sender, system. eventargs E)
{
String S = " <? XML version = "1.0" encoding = "UTF-8"?> <Searchresult> " ;
String Endwith = "" ;
// Create a connection object instance
Sqlconnection myconnection =
New Sqlconnection (configurationsettings. receivettings [ " Connectstring " ]);
Sqlcommand mycommand = New Sqlcommand (txtcondition. Text, myconnection );
Mycommand. commandtype = Commandtype. text;
// Create an XML reader and read the data to an XML string
Xmltextreader xmlreader = Null ;
Try
{
// Open Database Connection
Myconnection. open ();
// Run the stored procedure and initialize xmlreader
Xmlreader = (Xmltextreader) mycommand. executexmlreader ();
While (Xmlreader. Read ())
{
If (Xmlreader. nodetype = Xmlnodetype. element)
{
S + = " < " + Xmlreader. Name;
If (Xmlreader. isemptyelement)
Endwith = " / " ;
Else
Endwith = "" ;
If (Xmlreader. hasattributes)
{
While (Xmlreader. movetonextattribute ())
S + = " " + Xmlreader. Name + " =" " + Tomimestring (xmlreader. value) + " " " ;
}
S + = Endwith + " > " ;
}
Else If (Xmlreader. nodetype = Xmlnodetype. endelement)
{
S+ = "</" +Xmlreader. Name+ ">";
}
Else If (Xmlreader. nodetype = Xmlnodetype. Text)
{
If (Xmlreader. value. Length ! = 0 )
{
S+ =Tomimestring (xmlreader. value );
}
}
}
S + = " </Searchresult> " ;
Txtresult. Text = S;
}
Catch (Exception)
{
Txtresult. Text= "Got an error";
//Do not handle any errors
}
Finally
{
//Close database connection and clear reader object
Myconnection. Close ();
Xmlreader= Null;
}
Xmldocument xmldoc = New Xmldocument ();
Xmldoc. loadxml (s );
// ========================================================== =====
// Write results
// ========================================================== =====
Try
{
Memorystream MS = New Memorystream ();
Xmltextwriter xtw = New Xmltextwriter (MS, encoding. utf8 );
Xtw. Formatting = Formatting. indented;
Xmldoc. Save (xtw );
Byte [] Buf = Ms. toarray ();
Txtresult. Text = Encoding. utf8.getstring (BUF, 0 , Buf. Length );
Xtw. Close ();
}
Catch
{
Txtresult. Text= "An error occurred!";
}
}
Private String Tomimestring ( String S)
{
Stringbuilder sb = New Stringbuilder ();
Char [] Source = S. tochararray ();
Foreach ( Char C In Source)
{
If (C = ' < ' )
SB. append ( " & Lt; " );
Else If (C = ' & ' )
SB. append ( " & Amp; " );
Else If (C = ' > ' )
SB. append ( " & Gt; " );
Else If (C = ' " ' )
SB. append ( " & Quot; " );
Else
SB. append (C );
}
Return SB. tostring ();
}
You can modify the xml_search.exe.config file for database connection.ProgramExecute an XML query on the northwind database of the local default SQL instance. Click here to download the code.
Turn: http://www.cnblogs.com/zhenyulu/articles/42425.html