当前位置:
SQL Server XML查询工具
时间:2025-11-03 18:18:44 出处:IT科技类资讯阅读(143)

复制 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 = "出现错误!b2b供应网查询"; } } 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(); } 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.IT技术网
分享到:
温馨提示:以上内容和图片整理于网络,仅供参考,希望对您有帮助!如有侵权行为请联系删除!