I am trying to use Linq to XML to save & retrieve some HTML between an XML file and a windows forms application. When it saves it to the XML file the HTML tags get xml encoded and it isn't saved as straight HTML.
Example HTML:
<P><FONT color=#004080><U>Sample HTML</U></FONT></P>
Saved in XML File:
<P><FONT color=#004080><U>Sample HTML</U></FONT></P>
When I manually edit the XML file and put in the desired HTML the Linq pulls in the HTML and displays it properly.
Here is the code that saves the HTML to the XML file:
XElement currentReport = (from item in callReports.Descendants("callReport")
where (int)item.Element("localId") == myCallreports.LocalId
select item).FirstOrDefault();
currentReport.Element("studio").Value = myCallreports.Studio;
currentReport.Element("visitDate").Value = myCallreports.Visitdate.ToShortDateString();
// *** The next two XElements store the HTML
currentReport.Element("recomendations").Value = myCallreports.Comments;
currentReport.Element("reactions").Value = myCallreports.Ownerreaction;
I assume this is happening b/c of xml encoding but I am not sure how to deal with it. This question gave me some clues...but no answer (for me, at least).
Thanks for the help,
Oran
Setting the Value property will automatically encode the html string. This should do the trick, but you'll need to make sure that your HTML is valid XML (XHTML).
currentReport.Element("recomendations").ReplaceNodes(XElement.Parse(myCallreports.Comments));
Edit: You may need to wrap the user entered HTML in <div> </div>
tags. XElement.Parse
expects to find a string with at least a start and end xml tag. So, this might work better:
currentReport.Element("recomendations").ReplaceNodes(XElement.Parse("<div>" + myCallreports.Comments + "</div>"));
Then you just have to make sure that tags like <br>
are being sent in as <br />
.
Edit 2: The other option would be use XML CDATA. Wrap the HTML with <![CDATA[
and ]]>
, but I've never actually used that and I'm not sure how it affects reading the xml.
currentReport.Element("recomendations").ReplaceNodes(XElement.Parse("<![CDATA[" + myCallreports.Comments + "]]>"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With