2016-10-03 116 views
2

我在操作/瀏覽DataSet時遇到了問題,我將其作爲自動生成的XML文件提取。我的目標是將某些節點放入SQL表中的列。操縱數據集

我的XML

<root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:mix="http://www.jcp.org/jcr/mix/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0" xmlns:rep="internal" xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:sv="http://www.jcp.org/jcr/sv/1.0"> 
     <submission name="entry0"> 
      <entry name="firstName">Name</entry> 
      <entry name="School">The University of College</entry> 
      <entry name="ExpectedYearofEntry">2019</entry> 
      <entry name="mailingAddress">Some st</entry> 
     </submission> 
     <submission name.......... 
</root> 

我想這一點:

string xmlFile = @"xml.xml"; 

DataSet dataSet = new DataSet(); 
dataSet.ReadXml(xmlFile, XmlReadMode.InferSchema); 
DataTable table = dataSet.Tables["entry"]; 
IEnumerable<DataRow> row = table.AsEnumerable(); 

當我打破我可以看到行中的數據;也就是ItemArray 0包含firstName和'Name'。但我無法弄清楚如何從行中獲取這些數據。

回答

0

你可以使用像SqlBulkCopy有效地插入所有這些行到表中。但是你必須爲DataSet中的每個表執行此操作。

很好的例子:https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx 一旦你有一個DataTable插入。

if (dt.Rows.Count > 0) 
{ 
    string consString = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString; 
    using (SqlConnection con = new SqlConnection(consString)) 
    { 
     using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) 
     { 
      //Set target table 
      sqlBulkCopy.DestinationTableName = "dbo.Customers"; 

      //Map the DataTable columns with the database table 
      sqlBulkCopy.ColumnMappings.Add("Id", "CustomerId"); 
      sqlBulkCopy.ColumnMappings.Add("Name", "Name"); 
      sqlBulkCopy.ColumnMappings.Add("Country", "Country"); 
      con.Open(); 
      sqlBulkCopy.WriteToServer(dt); 
      con.Close(); 
     } 
    } 
}