This blog article shows you how to insert a XML file into MS SQL Server XML column. The code snippet below writes to the XML column in SQL Server database table.
static void Main(string[] args)
{
string xmlFilePath = “XMLFileRemoveUTF8.xml”;
string connectionString = “Server=.;Database=poc;Integrated Security=True;TrustServerCertificate=true”;
int id = 1;
// Read the XML file
string xmlContent = File.ReadAllText(xmlFilePath);
// Insert the XML into the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = “INSERT INTO tblMyXml (id, MyXml) VALUES (@id, @xml)”;
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue(“@id”, id);
command.Parameters.AddWithValue(“@xml”, xmlContent);
command.ExecuteNonQuery();
}
}
Console.WriteLine(“XML inserted into the database successfully.”);
}
Also: Convert SqlDataReader to Json
Source code download: https://github.com/chanmmn/database/tree/main/2024/ConAppWriteXMLSql?WT.mc_id=DP-MVP-36769