Philip Grooms

Philip Grooms

  • NA
  • 39
  • 1.4k

Import xml data into existing SQL Table using c#

Jan 27 2023 6:49 PM

We will have some XML documents saved in a shared folder and I need to import them as insert/update into an existing SQL Server table that contains the correct XML document tags.

I would like for my desktop app to load a document, import as insert or update if it already exists and then upon success delete that document from the folder and go to the next one.

Can anyone show me some examples that I might be able to work with?

This is what I have tried so far, however I get errors that the PalletID is not part of the datasource.

SqlConnection con = new SqlConnection(MyGlobals.SQLConnStr()); 

DataSet reportData = new DataSet(); 
reportData.ReadXml("C:\Users\admin\Desktop\GitHub\*.xml"); 

SqlBulkCopy sbc = new SqlBulkCopy(con); 
sbc.DestinationTableName = "PalletSpecs"; 
sbc.ColumnMappings.Add("PalletId", "PalletSpecs.PalletID");            
sbc.ColumnMappings.Add("_PalletLength", "_PalletLength"); 
sbc.ColumnMappings.Add("_PalletWidth", "_PalletWidth"); 
sbc.ColumnMappings.Add("_PalletClass", "_PalletClass"); 
sbc.ColumnMappings.Add("_PalletStyle", "_PalletStyle"); 
sbc.ColumnMappings.Add("_EntryStyle", "_EntryStyle"); 
sbc.ColumnMappings.Add("_Number", "_LumberNumber"); 
sbc.ColumnMappings.Add("_Style", "_Style"); 
sbc.ColumnMappings.Add("_Location", "_Location"); 
sbc.ColumnMappings.Add("_Type", "_Type"); 
sbc.ColumnMappings.Add("_Length", "_Length"); 
sbc.ColumnMappings.Add("_Width", "_Width"); 
sbc.ColumnMappings.Add("_Height", "_Height"); 
sbc.ColumnMappings.Add("_FasternerID", "_FasternerID"); 
sbc.ColumnMappings.Add("_FasternerType", "_FasternerType"); 
sbc.ColumnMappings.Add("_Number", "_Number"); 
sbc.ColumnMappings.Add("Note", "Note"); 

con.Open(); 
sbc.WriteToServer(reportData.Tables[0]); 
con.Close();

Here is an example of my xml file:

<PalletId>AACEAS1</PalletId>
<PalletClassification PalletLength="48.000000" PalletWidth="40.000000" PalletClass="STRINGER-CLASS" PalletStyle="DOUBLE-FACE NON-REVERSIBLE" EntryStyle="PARTIAL 4-WAY" TopDeckStyle="TOP DECKBOARD" BottomDeckStyle="BOTTOM DECKBOARD" BottomDeckOrientation="PERPENDICULAR" EstimatedWeight="40.000000"/>
<Components>
<Component Number="2" Style="DECKBOARD" Location="TOP DECK" Type="NEW LUMBER" Length="40.000000" Width="5.500000" Height="0.500000">
<Lumber Type="NEW LUMBER">
<LumberID>Pine</LumberID>
<MoistureContent>Green</MoistureContent>
<SpeciesCombo SpeciesName="Southern Yellow Pine" Grade="Standard &BTR" Precentage="100"/>
</Lumber>
</Component>
<Component Number="5" Style="DECKBOARD" Location="TOP DECK" Type="NEW LUMBER" Length="40.000000" Width="3.500000" Height="0.500000">
<Lumber Type="NEW LUMBER">
<LumberID>Pine</LumberID>

Can anyone help a newbie?


Answers (1)