我用C#从SQLite导出到XML。我需要将此XML导入到空SQLite数据库。我还需要在插入时验证内容。我的XML:
<root>
<name1>
<names>
<id>5</id>
<class>space</class>
<from>Germany</from>
<to>France</to>
<through>
<via>
<id>7</id>
<route>Vienna<route>
</via>
</through>
</names>
<mynames3>Black</mynames3>
<mynames4>Hawkins</mynames4>
</name1>
<name2>
<newNames>
<id>8</id>
<path>Road</path>
<dest>USA</dest>
<through>
<route1>
<id>5</id>
<naviagte>Britain</naviagte>
<naviagte2>Holland</naviagte2>
<naviagting2>
<naviagtes2>
<naviagte5>France</naviagte5>
<naviagte6>US</naviagte6>
<naviagte7>Canada</naviagte7>
<naviagtes2>
</naviagting2>
<naviagte11>Russia</naviagte11>
<naviagte12>Poland</naviagte12>
</route1>
<route1>
<id>2</id>
<naviagte>Canada</naviagte>
</route1>
</through>
</newNames>
</name2>
<name3>H2V3</name3>
<name4>H5V8</name4>
</root>
怎么办?我试了试:
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dataPath + "/Empty.db3");
sqlCon.Open();
SqliteCommand sqlCmd = new SqliteCommand(sqlCon);
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(syncPath, tableName + "_4.xml"), XmlReadMode.ReadSchema);
foreach(DataTable dt in ds.Tables)
{
//Get field names
string sqlString = "INSERT into " + tableName + " (";
string valString = "";
var sqlParams = new string[dt.Rows[0].ItemArray.Count()];
int count = 0;
foreach(DataColumn dc in dt.Columns)
{
sqlString += dc.ColumnName + ", ";
valString += "@" + dc.ColumnName + ", ";
sqlParams[count] = "@" + dc.ColumnName;
count++;
}
valString = valString.Substring(0, valString.Length - 2);
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ") VALUES (" + valString + ")";
sqlCmd.CommandText = sqlString;
foreach(DataRow dr in dt.Rows)
{
for (int i = 0; i < dr.ItemArray.Count(); i++)
{
sqlCmd.Parameters.AddWithValue(sqlParams[i], dr.ItemArray[i] ?? DBNull.Value);
}
sqlCmd.ExecuteNonQuery();
}
}
1条答案
按热度按时间pokxtpni1#
首先使用XML2CSharp网站生成C#类。反序列化到生成的类中。接下来创建类以存储反序列化的数据。将这些创建为表。最后将反序列化的数据复制到SQLite容器类中,然后存储这些类: