使用XML实现Flash与.NET通信

本实例的原理和客户端代码请参看:使用XML实现Flash与服务器通信。此处只讲解怎样用C#实现相同功能。如下面代码:

<%@ Page Language="C#" %> 
<%@ Import Namespace="System.IO" %> 
<%@ Import Namespace="System.Xml" %> 
<%@ Import Namespace="System.Data.OleDb" %> 
<script runat="server"> 
private void Page_Load(object sender, System.EventArgs e)  
{ 
    Stream inStream=Request.InputStream; 
    if (inStream.Length > 0) 
    { 
        XmlReader reader = XmlReader.Create(Request.InputStream); 
        reader.ReadToFollowing("student"); 
        string name = reader.GetAttribute("name"); 
        reader.Close(); 
  
        XmlWriterSettings settings = new XmlWriterSettings(); 
        settings.Indent = true; 
        XmlWriter writer = XmlWriter.Create(Response.Output, settings); 
  
        writer.WriteStartElement("item"); 
        OleDbConnection con = new OleDbConnection(); 
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
            "Data Source=|DataDirectory|Exam.mdb"; 
        string sqlStr = "Select StudentID,Name,ClassName FROM Student" + 
            " Where Name LIKE '" + name + "%'"; 
        OleDbCommand cmd = new OleDbCommand(sqlStr, con); 
        con.Open(); 
        OleDbDataReader dr = cmd.ExecuteReader(); 
        while (dr.Read()) 
        { 
            writer.WriteStartElement("student"); 
            writer.WriteAttributeString("id", dr[0].ToString()); 
            writer.WriteAttributeString("name", dr[1].ToString()); 
            writer.WriteAttributeString("cname", dr[2].ToString()); 
            writer.WriteEndElement(); 
        } 
        writer.WriteEndElement(); 
  
        writer.Close(); 
        dr.Close(); 
        con.Close(); 
    } 
} 
</script>

因为我们只是对XML数据进行查询,所以好使用XMLReader和XmlWriter类,它们可以提供对XML文件快速、非缓存、只进读写,所以速度比用XmlDocument类快得多。而且它不需要服务器安装有MSXML2.DOMDocument组件,其扩展性更强。我租用的服务器就没有安装这个组件,怪不得我用ASP作为后台在服务器运行会出错。实际上,大家看到的Demo的后台用的是C#。

发表评论