1

I can insert my XML easily into my database table, but i follow this exhausting manner as seen in my down code using LINK, which is perfectly tested. But, I wonder if I can find a way to read all my XML descendants elements of "Level" node, using iteration of all child tagnames, because when I make any change to my XML file, I would have to change my LINK code once again,and usually i'll face some errors when i use this exhausting manner. Please help improve this code:

try
{
    XElement d = XElement.Parse(richTextBox1.Text.ToString());

        var people = (from Level in d.Descendants("Level")
                      select new
                      {
                          ID = Convert.ToInt32(Level.Element("ID").Value),
                          Day1 = Level.Element("Day1").Value,
                          Day2 = Level.Element("Day2").Value,
                          Day3 = Level.Element("Day3").Value,
                          Day4 = Level.Element("Day4").Value,
                          Day5 = Level.Element("Day5").Value,
                          Day6 = Level.Element("Day6").Value,
                          Day7 = Level.Element("Day7").Value
                      }).ToList();
        foreach (var item in people)
        {
            //Insert and Update                    
            datacommand1.CommandText = "Insert Into MyTable(ID,Day1,Day2,Day3,Day4,Day5,Day6,Day7) values(" + item.ID + ","  + "','" + item.Day1 + "','" + item.Day2 + "','" + item.Day3 + "','" + item.Day4 + "','" + item.Day5 + "','" + item.Day6 + "','" + item.Day7 + "')";
            datacommand1.ExecuteNonQuery();                        
        }                    
}

my XML file seems like that:

<level>
    <id> 101 </id>
    <Day1> task 1</Day1>
    <Day2> task 2</Day2>
    <Day3> task 3</Day3>
    <Day4> task 4</Day4>
    <Day5> task 5</Day5>
    <Day6> task 6</Day6>
    <Day7> task7 </Day7>

</level>
4

1 回答 1

1

您可能不想为文件中的每个标记声明一个变量,而是尝试遍历所有变量,提取每个变量的名称和值,并在运行时从这些变量中编写 SQL 语句,无论它们是什么。尝试这样的事情:

IEnumerable<XElement> items = d.Descendants("level").Elements();
string names = string.Empty;
string values = string.Empty;
foreach (XElement item in items)
{
    names += item.Name + ",";
    values += "@" + item.Name + ",";
    IDbDataParameter parameter = datacommand1.CreateParameter();
    parameter.ParameterName = "@" + item.Name;
    parameter.DbType = DbType.String;
    parameter.Value = item.Value;
    datacommand1.Parameters.Add(parameter);
}
datacommand1.CommandText = "INSERT INTO MyTable (" + names.Substring(names.Length - 1) + ") VALUES (" + values.Substring(values.Length - 1) + ");";
datacommand1.ExecuteNonQuery();

这会基于 XML 结构动态构建命令,并用那里的数据填充其参数。但是这样做依赖于表结构将与文件中的完全相同的事实,并且在结构更改时仍需要手动更新模式,但只要它们同步就应该没问题。

编辑

关于数据类型,我能想到两种选择。保持原样,无论如何都将所有内容作为字符串发送,并依靠数据库引擎来解析、验证并将其转换为数字(取决于您使用的数据库,这可能是可能的,也可能不是,但我想它不是很少见)。或者修改代码以将特殊字段与循环分开(并从中排除)并一一添加,并相应地指定它们的类型。如果数字列是固定的,例如 ID,而其他所有内容都是文本,这很容易做到。

于 2013-10-17T00:15:36.280 回答