'How to convert XML columns to rows in SQL database?
I am trying to import an XML invoice to SQL database. After some research, I have managed to put it in SQL database but it has x rows whereas it should be a single row and x columns. Most of the sources I have read had examples of XML tables with multiple rows and XML files themselves were much simpler than this invoice file I am working with. I am aware the issue is probably related with columnMapping but could not figure how to fix it. Any help is appreciated.
Unfortunately I can't share the original invoice but I have found something similar: http://docs.oasis-open.org/ubl/os-UBL-2.2/xml/UBL-Invoice-2.1-Example.xml
private void buttonImport_Click(object sender, EventArgs e){
string XMlFile = textBoxBrowse.Text;
if (File.Exists(XMlFile))
{
DataTable dt = CreateDataTableXML(XMlFile);
if (dt.Columns.Count == 0)
dt.ReadXml(XMlFile);
string Query = CreateTableQuery(dt);
SqlConnection con = new SqlConnection(strcon);
con.Open();
cmd.ExecuteNonQuery();
// Table Creation
cmd = new SqlCommand(Query, con);
int check = cmd.ExecuteNonQuery();
if (check != 0)
{
// Copy Data from DataTable to Sql Table
using (var bulkCopy = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); }
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = dt.TableName;
bulkCopy.WriteToServer(dt);
}
MessageBox.Show("Table Created Successfully");
}
con.Close();
}
}
public DataTable CreateDataTableXML(string XmlFile) {
XmlDocument doc = new XmlDocument();
doc.Load(XmlFile);
DataTable Dt = new DataTable();
try
{
Dt.TableName = GetTableName(XmlFile);
XmlNode NodeStruct = doc.DocumentElement.ChildNodes.Cast<XmlNode>().ToList()[0];
foreach (XmlNode columna in NodeStruct.ChildNodes)
{
Dt.Columns.Add(columna.Name, typeof(String));
}
XmlNode Files = doc.DocumentElement;
foreach (XmlNode File in Files.ChildNodes)
{
List<string> Values = File.ChildNodes.Cast<XmlNode>().ToList().Select(x => x.InnerText).ToList();
Dt.Rows.Add(Values.ToArray());
}
}
catch (Exception ex)
{
}
return Dt;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|