2016-11-08 79 views
1

我有一个.xml文件,其中包含30个表,并且我想要读取所有表并将数据插入到SQL Server数据库中而不声明任何变量,意味着一切都是动态发生的如何使用C#将XML文件数据动态导入到SQL Server中

<person> 
    <created_by>admin</created_by> 
    <created_on_timestamp>2014-11-19T14:13:54.000Z</created_on_t‌​imestamp> 
    <date_of_birth>1990-04-04</date_of_birth> 
    <last_modified_by>admin</last_modified_by> 
    <last_modified_on>2014-11-21T13:29:49.000Z</last_modified_on‌​> 
    <logon_user_id>P10621</logon_user_id> 
    <logon_user_is_active>true</logon_user_is_active> 
    <logon_user_name>P10621</logon_user_name> 
    <person_id>3478</person_id> 
    <person_id_external>P10621</person_id_external> 
    <personal_informatio> 

<last_modified_by>admin</last_modified_by> 
<last_modified_on>2014-11-21T14:45:49.000Z</last_modified_on‌​> 
<last_name>Singh</last_name> 
<marital_status>S</marital_status> 
<nationality>IND</nationality> 
<salutation>MR</salutation> 
<start_date>2014-05-01</start_date> 
<personal_information_ind> 
    <country>IND</country> 
    <created_by>admin</created_by> 
    <created_on_timestamp>2014-11-21T13:50:33.000Z</created_on_t‌​imestamp> 
    <custom_string1>hi</custom_string1> 
    <genericNumber1>22</genericNumber1> 

<address_information> 
    <address1>-0</address1> 
    <address2>Villa -342,Omax Panorama City</address2> 
    <address3>-0</address3> 
    <address4>[email protected]</address4> 
    <address5>919828513833</address5> 
    <address_type>home</address_type> 
    <city>Bhiwadi</city> 
    <country>IND</country> 
    <county>India</county> 
    <created_by>admin</created_by> 
    <created_on_timestamp>2014-11-21T15:09:41.000Z</created_on_t‌​imestamp> 
    <end_date>9999-12-31</end_date> 
    <is_global_model_address>false</is_global_model_address> 
    <last_m 
+0

您能否添加更多细节,即xml文件的外观如何?分享你的尝试。 – coderz

+0

我试着先读取xml文件并插入数据集,然后使用连接组合所有表,然后使用cmd.Parameters.AddWithValue声明xml和数据库的字段,然后在更改xml文件时插入数据库bt,然后我们必须更改所有应用程序BT我想只有当XML文件恰克我的应用程序运行正常为所有类型的XML文件 –

+0

管理 2014-11-19T14:13:54.000Z 1990-04 -04 管理 2014-11-21T13:29:49.000Z P10621 P10621 P10621

回答

0
XmlDocument doc = new XmlDocument(); 
doc.Load("yourxmlfile.xml"); 

string databasename = doc.DocumentElement.Name; 

foreach (XmlNode node in doc.SelectNodes("/" + databasename + "/*[starts-with(name(), 'SourceTableName')]")) 
{ 
    string tablename = node.Attributes["targetTable"].Value; 
    string Columns = ""; 
    string Values = ""; 

    foreach (XmlNode field in node.SelectNodes("Field")) 
    { 
     Columns += (!string.IsNullOrEmpty(Columns) ? ", " : "") + field.Attributes["targetField"].Value; 
     Values += (!string.IsNullOrEmpty(Values) ? ", " : "") + "'" + field.InnerText + "'"; 
    } 

    //Generate insert statement 
    string statement = string.Format("Insert Into {0}.{1} ({2}) Values ({3})", 
            databasename, 
            tablename, 
            Columns, 
            Values); 

    Console.WriteLine(statement); 
} 
相关问题