I've write a quick code to try getting elements from an XML file and put them in an excel table but I don't get anyhting out of my nodes. I don't understand why.
I've been trying different mean of getting what I need from my nodes using the microsoft documentation of XMLDocument but the result is always the same, it's printing me empty lines.
[STAThread]
static void Main(string[] args)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
XmlDocument xmlDocument = new XmlDocument();
System.Data.DataTable table = new System.Data.DataTable();
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook workBook;
Microsoft.Office.Interop.Excel.Worksheet workSheet;
int rowCount = 1;
openFileDialog.Filter = "XML Files|*.xml";
openFileDialog.Title = "Select the SMS backup";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
xmlDocument.PreserveWhitespace = true;
try
{
xmlDocument.Load(openFileDialog.FileName);
}
catch (System.IO.FileNotFoundException)
{
}
table.Columns.Add("Contact name", typeof(string));
table.Columns.Add("Date", typeof(DataFormats));
table.Columns.Add("Message", typeof(string));
foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes)
{
System.Diagnostics.Debug.WriteLine(node.InnerText);
if (node.InnerText.Contains("contact_name"))
{
table.Rows.Add(
node.Attributes["contact_name"]?.InnerText,
node.Attributes["readable_date"]?.InnerText,
node.Attributes["body"]?.InnerText
);
}
}
try
{
excel = new Microsoft.Office.Interop.Excel.Application
{
Visible = true,
DisplayAlerts = false
};
workBook = excel.Workbooks.Add(Type.Missing);
workSheet = (Microsoft.Office.Interop.Excel.Worksheet) workBook.ActiveSheet;
workSheet.Name = "SMS backup";
foreach (System.Data.DataRow dataRow in table.Rows)
{
rowCount += 1;
for (int i = 1; i <= table.Columns.Count; i++)
{
workSheet.Cells[rowCount, i] = dataRow[i - 1].ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
workSheet = null;
workBook = null;
}
}
}