1

谁能帮助我使用 C# 将 XML 数据(我从远程REST 服务获得)插入到我的 SQL Server 数据库中?

提前致谢。

代码

HttpWebRequest myHttpWebRequest = WebRequest.Create("http://api.asicentral.com/v1/news.xml") as HttpWebRequest;

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = 
    new StreamReader(myHttpWebResponse.GetResponseStream(), enc);

string Response = loResponseStream.ReadToEnd();
myHttpWebResponse.Close();
4

3 回答 3

1
    [WebMethod]
    public void XMLPersing()
    {
        var XMLDATA = "";

        WriteLogCLS objWriteLog = new WriteLogCLS();
        Stream receiveStream = HttpContext.Current.Request.InputStream;
        receiveStream.Position = 0;
        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);      //For xml persing..
        XMLDATA = readStream.ReadToEnd();
        readStream.Close();

      objWriteLog.WriteLog(Convert.ToString(XMLDATA));
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Log/Exception/Sample.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);
        xmlreader.Close();
        if (ds.Tables.Count != 0)
        {
            var strCon = string.Empty;
            strCon = ConfigurationManager.AppSettings["constring"];
            SqlCommand cmdInsertXMLData = new SqlCommand();
            SqlConnection SqlConn;
            SqlConn = new SqlConnection(strCon);
            try
            {
                cmdInsertXMLData = new SqlCommand("usp_InsertXML", SqlConn);
                cmdInsertXMLData.CommandType = CommandType.StoredProcedure;
                // cmdInsertLoginDetails.Parameters.Add("@XMLdata", SqlDbType.Xml).Value = ds.GetXml();
                cmdInsertXMLData.Parameters.AddWithValue("@XMLdata", SqlDbType.Xml);

                if (SqlConn.State == ConnectionState.Closed)
                {
                    SqlConn.Open();
                }
                cmdInsertXMLData.ExecuteNonQuery();
                // response = cmdInsertLoginDetails.Parameters["@Message"].Value.ToString();
            }
            catch (Exception ex)
            {
                objWriteLog.WriteLog("Error on XML Persing : " + ex.Message);
                // response = "Error";
            }
            finally
            {
                if (cmdInsertXMLData != null)
                {
                    cmdInsertXMLData.Dispose();
                }
                if (SqlConn.State == ConnectionState.Open)
                {
                    SqlConn.Close();
                    SqlConn.Dispose();
                }
                objWriteLog = null;
            }
            // return response  ;

        }
    }
}
于 2015-03-20T06:52:34.090 回答
1

开始学习 ADO.Net http://www.csharp-station.com/Tutorial/AdoDotNet/lesson01

或者试试这个实体框架代码优先方法http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

好的,上面的内容有点生硬,那为什么要将Web服务响应存储到数据库中呢?

为了做任何有意义的事情,您可能需要解析 xml。您在这里有很多选择。一对突然想到的夫妇;将 xml 反序列化为强类型对象,或者使用 linq 创建匿名类型。最后,您可以使用 ADO.Net 或实体框架将对象存储到数据库中。

于 2012-06-19T10:39:20.227 回答
1

为了将此 XML 插入 SQL Server,您需要在 SQL Server 中有一个表,其列类型为XML

然后你可以使用一些非常简单的东西,比如:

string connectionString = "......";  // define your connection string here
string query = "INSERT INTO dbo.YourTableNameHere(XmlColumn) VALUES(@XmlContent)";

// set up SqlConnection and SqlCommand
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
    // define parameter for query and set its value to your XML response
    cmd.Parameters.Add("@XmlContent", SqlDbType.VarChar, -1);
    cmd.Parameters["@XmlContent"].Value = Response;    // assign your XML response here

    // open connection, execute INSERT, close connection
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();     
}

当然,如果您使用 Entity Framework 或其他 ORM 之类的东西,那么事情看起来会大不相同......这只是“直截了当”的纯 ADO.NET

于 2012-06-19T10:58:07.283 回答