I am writing a web application in C#.NET MVC 4. I have a web form which inserts data to an XML file within the APP_Data folder. I am wondering next if i can load this data into a sql server database and how i would go about doing this!
-
SQLServer has built-in functions to output any result out to XML format but I am not sure about how easy it is to do it the other way around and insert-from a XML file.djangofan– djangofan2014-01-10 01:07:22 +00:00Commented Jan 10, 2014 at 1:07
-
possible duplicate : Importing data from XML file to SQL databasehar07– har072014-01-10 01:19:50 +00:00Commented Jan 10, 2014 at 1:19
Add a comment
|
1 Answer
Super easy. I do something similar where I have a table with an Identity primary key column, a Created Date DateTime column, and a Data column that's type XML. You can insert the XML from .Net as a string. Instead of going through the labor of creating an XmlDocument, I just have strongly typed Model and serialize it to a string.
string xmlData;
var xmlSerializer = new XmlSerializer(model.GetType());
using (var sw = new StringWriter()) {
xmlSerializer.Serialize(sw, model);
xmlData = sw.ToString();
}
using (var efContext = new MyDbEntities()) {
evContext.Documents.Add(new Document() {
CreatedDate = DateTime.Now,
Data = xmlData
});
efContext.SaveChanges();
}