关键代码: 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