问题
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 = "<![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 = "<![CDATA[ " + s + " ]]>";
回答2:
Try this way:
newElement.InnerXml = "<![CDATA[ " + s + " ]]>";
来源:https://stackoverflow.com/questions/9473667/how-do-i-add-cdata-to-an-xml-file