How to save HTML in XML file using Linq to XML?

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:

&lt;P&gt;&lt;FONT color=#004080&gt;&lt;U&gt;Sample HTML&lt;/U&gt;&lt;/FONT&gt;&lt;/P&gt;

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 + "]]>"));

尝试使用currentReport.Element("studio").InnerXml而不是currentReport.Element("studio").Value

链接地址: http://www.djcxy.com/p/42648.html

上一篇: 安装.NET参考源代码(RSCC)

下一篇: 如何使用Linq to XML将XML保存在XML文件中?