Using xml files with xml column in linq to sql
October 27, 2008 – 3:28 amI was trying to read in some xml files and insert them into the database. I thought simple enough, just open the xml file, get a string representation of it and then use that to on the linq to sql object to save it on the database.
var Replay = new War3Replay
{
Winner = replay.winner,
Map = replay.map.Trim(),
GameLength = replay.gamelength,
Players = PlayersReduced.ToString(),
Races = new String(RacesReduced),
Checksum = replay.checksum,
DateSubmitted = DateTime.UtcNow,
SubmitterUserID = 1,
Chat = XMLchat
};
Here XMLchat is just a string representation of the xml text and Chat corresponds to a xml column. Sure enough I got this error.
Cannot implicitly convert type 'string' to 'System.Xml.Linq.XElement'
What the hell is an XElement? I googled around and then settled on this solution
var Replay = new War3Replay
{
....
Chat = new XElement("chat", chatnode.Current.OuterXml)
};
Complied fine and the application seemed to run smoothly. That is until you check out the data in the database. The XElement was saving all the data with the brackets being converted into entities. (lt; and gt;). From an xml standpoint, the data seemed useless. I headed over to stackoverflow and got this solution.
FileStream stream = new FileStream("data.xml", FileMode.Open);
XPathDocument document = new XPathDocument(stream);
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator chatnode = navigator.Select(navigator.Compile("/data/chat"));
chatnode.MoveNext();
var Replay = new War3Replay
{
Winner = replay.winner,
Map = replay.map.Trim(),
GameLength = replay.gamelength,
Players = PlayersReduced.ToString(),
Races = new String(RacesReduced),
Checksum = replay.checksum,
DateSubmitted = DateTime.UtcNow,
SubmitterUserID = 1,
Chat = XElement.Parse(chatnode.Current.OuterXml)
};
You had to let XElement call the parse function so that XElement can correctly shred the string representation into xml object. It seems kinda silly how linq to sql treats xml columns at the moment. In this example you have to open a file, read it, parse out the xml tree, get a string representation, pass it back to XElement so that it can build a xml tree, have linq to sql get a string representation and then send it over to Sql Server.