【发布时间】:2017-05-24 06:17:23
【问题描述】:
我正在尝试在属性值中包含 html 内容(例如 <tag attribute="<b>hi</b>"></tag>)。根据this,这似乎应该在字符串属性类型上默认完成,但是我得到了无效字符错误。有没有办法让 XAttribute 把它当作 CDATA 对待?
【问题讨论】:
标签: c# xml-parsing xelement
我正在尝试在属性值中包含 html 内容(例如 <tag attribute="<b>hi</b>"></tag>)。根据this,这似乎应该在字符串属性类型上默认完成,但是我得到了无效字符错误。有没有办法让 XAttribute 把它当作 CDATA 对待?
【问题讨论】:
标签: c# xml-parsing xelement
您不能将 XML 属性值指定为 CDATA。你可以做什么,你可以转义你想作为一个值放置的 xml:
<tag attribute="<b>hi</b>"></tag>
会变成
<tag attribute="<b>hi</b>"></tag>
如果你正在构建一个文档并且你想添加这个属性,你需要做的就是在 XAttribute 构造函数中添加 html:
var doc = new XDocument(new XElement("tag", new XAttribute("attribute", "<b>hi</b>")));
要将值作为 xml 文档获取,您可以使用以下代码:
var doc = XDocument.Parse("<tag attribute=\"<b>hi</b>\"></tag>");
var attributeValue = doc.Root.Attribute("attribute").Value;
var newDoc = XDocument.Parse(attributeValue);
【讨论】: