XML转DataTable
一:配置xml所在路径
private static string XmlFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "BasicData\\InitDBData.xml");
private static string ROOT_KEY = "db";
private static string ID_FIELD = "Id";
private static string CREATE_TIME_FIELD = "CreateTime";
二:导入XML文件进入DB
/// <param name="connectionString">Connection string.</param>
public static void Import(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentNullException("connectionString");
}
try
{
var tables = LoadXmlFile();
foreach (var table in tables)
{
if (HasTable(connectionString, table.Key) && IsTableEmpty(connectionString, table.Key))
{
SqlBulkCopyByDataTable(connectionString, table.Key, table.Value);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 验证表是否存在,是否为空
/// </summary>
/// <param name="connectionString">Database connection string.</param>
/// <param name="tableName">Table name.</param>
/// <returns>True if the check passed.</returns>
private static bool HasTable(string connectionString, string tableName)
{
if (string.IsNullOrWhiteSpace(connectionString) || string.IsNullOrWhiteSpace(tableName))
{
throw new ArgumentNullException("connectionString or tableName");
}
bool hasTable = false;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();