ASP .NET数据集到XML:存储和读取

时间:2010-07-09 13:49:41

标签: asp.net .net sql xml dataset

[以下是几乎完整的代码修改。目前在阅读时显示非法字符错误]。

我有一个C#ASP.NET应用程序,它正在从文件系统读取XML文件,然后将其加载到GridView控件中。在网格中我可以删除行。网格下方还有一个文件上传按钮,用于上传PDF文件并显示在网格中。我的代码基本上是this code

的修改版本

我的下一阶段工作涉及从数据库字段中读取XML数据作为String,而不是从XML文件中读取。为此,我想我可以从XML文件中读取,在aspx页面中进行更改,并将“数据集”写入名为“PDF_Storage”的数据库字段。我怎样才能做到这一点。至关重要的是,我需要能够将数据集转换为某种字符串格式进行存储。这是我的代码片段。

我的数据库是Oracle 10,但我可以找出Update sql语法。

示例XML文件:

 <DataSet>
    <PDF>
        <pdf>MyPDF1.pdf</pdf>
    </PDF>
    <PDF>
        <pdf>MyPDF2.pdf</pdf>
    </PDF>
    <PDF>
        <pdf>MyPDF3.pdf</pdf>
    </PDF>
</DataSet>

以及相应的代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Oracle.DataAccess.Client;
using System.Web.Configuration;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

public partial class XMLGridTest : System.Web.UI.Page
{
    public static string GetConnString()
    {
        return WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddata();
        }
    }
    void binddata()
    {
        DataSet ds = new DataSet();
      // ds.ReadXml(Server.MapPath("testxml.xml"));
        String strConnect = GetConnString();
        OracleConnection oracleConn = new OracleConnection();
        oracleConn.ConnectionString = strConnect;
        oracleConn.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = oracleConn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT PDF_Storage FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
        OracleDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            if (!reader.IsDBNull(0))
            {


              //## Line Below as the 'illegal characters' problem###
               ds.ReadXml(reader[0].ToString(), XmlReadMode.IgnoreSchema);
                 gv.DataSource = ds;
                gv.DataBind();

            }
            else
            {
                // Response.Write(reader.GetString(1));
                // TextBox1.Text = reader.GetString(1);
            }
        }
       // gv.DataSource = ds;//##Hard coded for XML. Works!
       //  gv.DataBind();

        //Finally, close the connection
        oracleConn.Close();


    }

    protected void Canceldata(object s, GridViewCancelEditEventArgs e)
    {
        gv.EditIndex = -1;
        binddata();
    }

    protected void pageddata(object s, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;
        binddata();
    }

    protected void insert(object sender, EventArgs e)
    {
        /////////////////////////////////File Upload Code/////////////////////////////////
        // Initialize variables
        string sSavePath = "ParcelPDF/"; ;
        if (fileupload.PostedFile == null)
        {
            Label1.Text = "Must Upload a PDF file!";
            return;
        }
        HttpPostedFile myFile = fileupload.PostedFile;
        int nFileLen = myFile.ContentLength;

        // Check file extension (must be JPG)
        if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".pdf")
        {
            Label1.Text = "The file must have an extension of .pdf";
            return;
        }
        // Read file into a data stream
        byte[] myData = new Byte[nFileLen];
        myFile.InputStream.Read(myData, 0, nFileLen);
        // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an incremental numeric until it is unique
        string sFilename = System.IO.Path.GetFileName(myFile.FileName);
        int file_append = 0;
        while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
        {
            file_append++;
            sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".pdf";
        }

        // Save the stream to disk
        System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
        newFile.Write(myData, 0, myData.Length);
        newFile.Close();
        binddata();
        DataSet ds = gv.DataSource as DataSet;
        DataRow dr = ds.Tables[0].NewRow();
        // dr[0] = pdf.Text;
        dr[0] = sFilename.ToString();
        ds.Tables[0].Rows.Add(dr);
        ds.AcceptChanges();
        string blah = "blah";
        Response.Write(ds.Tables.ToString());
        //  ds.WriteXml(Server.MapPath("testxml.xml"));
        String strConnect = GetConnString();
        OracleConnection oracleConn = new OracleConnection();
        oracleConn.ConnectionString = strConnect;
        oracleConn.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = oracleConn;
        cmd.CommandType = CommandType.Text;
        // cmd.CommandText = "SELECT OBJECTID,COMMENTS FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
        cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
        StringWriter SW = new StringWriter();
        ds.WriteXml(SW);
        cmd.Parameters.Add(":PDF_Storage", SW.ToString());
        cmd.ExecuteNonQuery();
        oracleConn.Close();
        binddata();
    }

    protected void Deletedata(object s, GridViewDeleteEventArgs e)
    {
        binddata();
        DataSet ds = gv.DataSource as DataSet;
        ds.Tables[0].Rows[gv.Rows[e.RowIndex].DataItemIndex].Delete();
        //  ds.WriteXml(Server.MapPath("testxml.xml"));//Disabled now. Do database. Irfan. 07/09/10
        String strConnect = GetConnString();
        OracleConnection oracleConn = new OracleConnection();
        oracleConn.ConnectionString = strConnect;
        oracleConn.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = oracleConn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
        StringWriter SW = new StringWriter();

        ds.WriteXml(SW,XmlWriteMode.IgnoreSchema);
        Regex regex = new Regex(@"(\r\n|\r|\n)+");
        string newText = regex.Replace(SW.ToString(), "");
        cmd.Parameters.Add(":PDF_Storage", newText);
        cmd.ExecuteNonQuery();
        oracleConn.Close();
        binddata();
        string blah = "blah";
    }

1 个答案:

答案 0 :(得分:0)

以下是我过去的做法。对于插入,您基本上只需将数据集的xml表示写入字符串并将其直接保存到数据库中的字段。在这种情况下,我利用Sql Server 2008和数据库字段的XML数据类型。我认为Oracle中的数据类型是XMLTYPE。

插入

public static void InsertDataSet(string key, DataSet dataSet)
{
  string xml = string.Empty;

  using (MemoryStream ms = new MemoryStream())
  {
    dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);

    ms.Position = 0;

    using (StreamReader sr = new StreamReader(ms))
    {
      xml = sr.ReadToEnd();
    }

    using (SqlServerConnection c = new SqlServerConnection(connectionString))
    {
      c.command.CommandType = CommandType.StoredProcedure;
      c.command.CommandText = "some stored procedure to do the insert";
      c.command.Parameters.Clear();

      c.command.Parameters.Add(new SqlParameter("@key", key));
      c.command.Parameters.Add(new SqlParameter("@xml", xml));

      c.command.ExecuteNonQuery();
    }
  }
}

将数据集从数据库中取出就像将数据库中的xml数据读回TextReader,然后构建新的DataSet一样简单。

获取:

public static DataSet GetDataSet(string key)
{
  using (SqlServerConnection c = new SqlServerConnection(connectionString))
  {
    c.command.CommandType = CommandType.StoredProcedure;
    c.command.CommandText = "some stored procedure to get the xml";
    c.command.Parameters.Clear();

    c.command.Parameters.Add(new SqlParameter("@key", key));

    dr = c.command.ExecuteReader();

    if (dr == null)
    {
      return null;
    }

    if (dr.HasRows)
    {
      while (dr.Read())
      {
        if (dr["xml_field"] != DBNull.Value)
        {
          TextReader tr = new StringReader(dr["xml_field"].ToString());

          result = new DataSet();
          result.ReadXml(tr, XmlReadMode.ReadSchema);
        }
      }
    }
  }

  return result;
}

希望这有帮助。

享受!