How do I add CDATA to an xml file?

女生的网名这么多〃 提交于 2020-01-06 12:53:23

问题


I have an existing xml file that holds notifications I want to display on my site. A snippet follows:

<contents>
  <item>
    <![CDATA[
        <a style="font-weight: bold;" href="http://engadget.com">Engadget</a>
    ]]>
  </item>
  <item>
    <![CDATA[
        <a style="font-weight: bold;" href="http://cnn.com">CNN</a>
    ]]>
  </item>
</contents>

I'm trying to open this document and add new "items" to it, but I can't:

        foreach (string s in notifications)
        {
            XmlElement newElement = doc.CreateElement("item");
            newElement.InnerXml = "&lt;![CDATA[ " + s + " ]]>";
            doc.DocumentElement.SelectNodes("/contents")[0].AppendChild(newElement);
        }

notifications is a List that I'm using to store the links. The error I'm getting is:

']]>' is not allowed in character data.

The notifications need to contain HTML, because of the way I'm displaying it. Thanks for looking, guys.


回答1:


Try using

newElement.AppendChild(doc.CreateCDataSection(s));

instead of

newElement.InnerXml = "&lt;![CDATA[ " + s + " ]]>";



回答2:


Try this way:

newElement.InnerXml = "&lt;![CDATA[ " + s + " ]]&gt;";


来源:https://stackoverflow.com/questions/9473667/how-do-i-add-cdata-to-an-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!