【问题标题】:Import Xml file into Database in Web app在 Web 应用程序中将 Xml 文件导入数据库
【发布时间】:2015-08-20 15:14:02
【问题描述】:

我正在尝试将 xml 读取到数据库。我在代码的第 1 行收到 systemnullreferenceException 错误:

StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("File.xml"));
string connStr = ConfigurationManager.ConnectionStrings["SERVERCONNECTION" +
                       "connection timeout=30"].ConnectionString;
DataSet ds = new DataSet();
ds.ReadXml(reader);
string strxml = XDocument.Load(reader).ToString();
SqlConnection sqlconn = new SqlConnection(connStr);
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection = sqlconn;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = "loadXML";
sqlcmd.Parameters.AddWithValue("@xmlstr", strxml);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();

【问题讨论】:

  • 假设这是一个 Web 应用程序,File.xml 是否位于根文件夹中?
  • 是的,它位于 Visual Studio 根文件夹中。
  • 嵌套函数调用总是一个坏主意。您需要在 使用它之前测试此调用的结果:System.Web.HttpContext.Current.Server.MapPath("File.xml")

标签: c# sql asp.net sql-server xml


【解决方案1】:

为了从 Xml 文件中读取 XmlDocument,您可以使用以下 ASP.NET/C# 代码 sn-p:

#region Read XML Document from file, ignore comments
/// <summary>
/// Read XML Document from file, ignore comments
/// </summary>
/// <param name="filePath">string</param>
/// <returns>XmlDocument</returns>
public static XmlDocument ReadXML(string filePath)
{
    XmlReaderSettings readerSettings;
    try
    {
        // check if document exists, otherwise exit
        if (!File.Exists(file)) { return null; }

        // reader settings to ignore comments
        readerSettings = new XmlReaderSettings();
        readerSettings.IgnoreComments = true;

        // load xml document
        using (XmlReader reader = XmlReader.Create(file, readerSettings))
        {
            XmlDocument _xmlDoc = new XmlDocument();
            _xmlDoc.Load(reader);
            return _xmlDoc;
        }
    }
    catch { return null; }
    finally { readerSettings = null; }
}
#endregion

我还建议将您的文件 File.xml 放在 ASP.NET 特殊的 App_Data 文件夹中。文件的完整路径可以使用以下语句组成:

string _fileFullPath = String.Concat (AppDomain.CurrentDomain.BaseDirectory, "App_Data/File.xml");

或者,您可以使用Server.MapPath() 方法(上面显示的方法要快得多)。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多