2

I have an xml file I want to save it's content into database to read it again.

I use XmlDocument to load the xml file and using InnerXml to save this xml.

This is my code

cmd.CommandText = @"INSERT INTO pages(BPMNID,XML) VALUES (@BPMNID,@XML)";
cmd.Parameters.AddWithValue("@BPMNID",2);
cmd.Parameters.AddWithValue("@XML", XDoc.InnerXml);

cmd.Connection = conn;
conn.Open();

try
{
    cmd.ExecuteNonQuery();
}

When run the previous code I get an exception

XML parsing :Unable to Switch the encoding

Hint: Xml column is a xml column

3
  • 2
    You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results... Commented Sep 20, 2015 at 9:14
  • Load the XML from the file into a string and then pass that into the SQL query. The SQL query doesn't know about XmlDocument:.. Commented Sep 20, 2015 at 9:18
  • @marc_s I try to make that and give me the same exception Commented Sep 20, 2015 at 9:22

1 Answer 1

1

Try to use code like this:

public void SaveXml(int id, string xmlFileName)
{
    // read your XML
    string xmlContent = File.ReadAllText(xmlFileName);

    // set up query
    string insertQuery = "INSERT INTO pages(BPMNID, XML) VALUES (@BPMNID, @XML)";

    using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
    using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
    {
        // define parameters
        cmd.Parameters.Add("@BPMNID", SqlDbType.Int).Value = id;
        cmd.Parameters.Add("@XML", SqlDbType.VarChar, -1).Value = xmlContent;

        // open connection, execute query, close connection
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

are you mean ReadAllText ? not LoadAllText
I get the same exception
@Ahmed: updated my code - using SqlDbType.VarChar, -1 seems to be working (at least for me), even with XML files containing the encoding="utf-8" in their header
Done, Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.