關鍵代碼:
private void btnSearch_Click(object sender, System.EventArgs e)
{
string s = "<?xml version="1.0" encoding="utf-8"?><SearchResult>";
string endWith = "";
// 建立連線物件執行個體
SqlConnection myConnection =
new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);
SqlCommand myCommand = new SqlCommand(txtCondition.Text, myConnection);
myCommand.CommandType = CommandType.Text;
// 建立 XML Reader,並讀取資料到 XML 字串中
XmlTextReader xmlReader = null;
try
{
// 開啟資料庫連接
myConnection.Open();
// 運行預存程序並初始化 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";
//不處理任何錯誤
}
finally
{
// 關閉資料庫連接並清理 reader 對象
myConnection.Close();
xmlReader = null;
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(s);
//=============================================
//將結果寫入
//=============================================
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 = "出現錯誤!";
}
}
private string ToMIMEString(string s)
{
StringBuilder sb = new StringBuilder();
char[] source = s.ToCharArray();
foreach(char c in source)
{
if(c=='<')
sb.Append("<");
else if(c=='&')
sb.Append("&");
else if(c=='>')
sb.Append(">");
else if(c=='"')
sb.Append(""");
else
sb.Append(c);
}
return sb.ToString();
}
資料庫連接可以通過修改 XML_Search.exe.config 檔案實現。程式對本地預設SQL執行個體的Northwind資料庫執行XML查詢。代碼下載請點這裡。
轉:http://www.cnblogs.com/zhenyulu/articles/42425.html