I'm writing a program where the user is doing some stuff and can save then the XML to his hard drive by using SaveFileDialog().

The current code of creating the XML-file is this (snippet which should work by everyone):

SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
using (XmlWriter writer = XmlWriter.Create(filename))
{
    try
    {
        writer.WriteStartDocument();

        writer.WriteStartElement("Questionnaire");
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "D:\\Schema.xsd");

        writer.WriteStartElement("Title");
        writer.WriteString("test");
        writer.WriteEndElement();
        writer.WriteStartElement("Number");
        writer.WriteString("1");
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.Flush();
        writer.Close();
    }
    catch (Exception ex)
    {
        System.Windows.MessageBox.Show(ex.Message);
    }
}
}

Now I also want to save the XML in my database. Either by using the column type xml in my table (I don't know how or what to save into this column) or by saving the full XML Code in a column of type nvarchar, which I actually would like to do.

How can I save the XML-file, which was created by a XmlWriter to my database (column of type xml or string which includes the xml)? By saying "which includes the xml" do I mean the full xml code, like

<Title>
    MyTitle
</Title>
有帮助吗?

解决方案

You may use the following constructor:

var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{ 
    // rest of your code above
    SaveToDb(sb.ToString());
}

And the SaveToDb method (validation and exception handling omitted):

private static void SaveToDb(string xml)
{
    using (var connection = new SqlConnection(conn))
    using (var command = new SqlCommand(
        "INSERT MyXmlTable VALUES (@XML)",
        connection))
    {
        command.Parameters.Add("XML", SqlDbType.Xml, xml.Length).Value = xml;
        connection.Open();
        var result = command.ExecuteNonQuery();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top