Milligran
Milligran

Reputation: 3171

How to serialize an object to XML that can be stored SQL database field of type XML

I have a c# web MVC application. I wish to serialize my model object to an XML to be stored in a SQL database field of type XML?

I was able to serialize to a file using:

   var writer = new System.Xml.Serialization.XmlSerializer(typeof(car));

   var file = new System.IO.StreamWriter(@"C:\car.xml");

   Writer.Serialize(file, car);

   file.Close();

How can I modify this code to serialize to type XML of which I can then store into my SQL table and field XML type

Upvotes: 0

Views: 2184

Answers (1)

sa_ddam213
sa_ddam213

Reputation: 43596

You can use StringWriter with XmlWriter to produce the xml string then save to your database

string xmlResult = string.Empty;
var xmlSerializer = new XmlSerializer(typeof(car));
using (var stringWriter = new StringWriter())
{
    using (var xmlWriter = XmlWriter.Create(stringWriter))
    {
        xmlSerializer.Serialize(xmlWriter, car);
    }
    xmlResult = stringWriter.ToString();
}

// save xmlResult to DB

Upvotes: 1

Related Questions