SQL Server XML查詢工具
導讀:SQL Server 提供了一個非常好用的客戶端檢索工具-查詢分析器,但是美中不足的是查詢分析器無法對XML查詢給出很好的結果,用戶無法完整查看XML結果集。上學期給IBM電子商務班講XML與WebService時,不得不自己寫了一個程序執(zhí)行XML檢索。雖然程序實在有些簡陋,但畢竟可以完成課堂演示的要求。
程序主體是通過sqlCommand的ExecuteXmlReader方法完成的。我添加了一些對特殊字符的MIME編碼(這一部分應當有現(xiàn)成代碼,不過我沒有找到,只好自己將就著寫了),以及XML格式處理功能。先貼上一些代碼,具體可以自己下載后看。希望多提寶貴意見。
關鍵代碼:
- private void btnSearch_Click(object sender, System.EventArgs e)
- {
- string s = "<?xml version="1.0" encoding="utf-8"?><SearchResult>";
- string endWith = "";
- // 創(chuàng)建連接對象實例
- SqlConnection myConnection =
- new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);
- SqlCommand myCommand = new SqlCommand(txtCondition.Text, myConnection);
- myCommand.CommandType = CommandType.Text;
- // 創(chuàng)建 XML Reader,并讀取數(shù)據(jù)到 XML 字符串中
- XmlTextReader xmlReader = null;
- try
- {
- // 打開數(shù)據(jù)庫連接
- 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
- {
- // 關閉數(shù)據(jù)庫連接并清理 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 = "出現(xiàn)錯誤!";
- }
- }
- private string ToMIMEString(string s)
- {
- StringBuilder sb = new StringBuilder();
- char[] ssource = 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();
- }
數(shù)據(jù)庫連接可以通過修改 XML_Search.exe.config 文件實現(xiàn)。程序對本地默認SQL實例的Northwind數(shù)據(jù)庫執(zhí)行XML查詢。
【編輯推薦】