I am trying to include html content inside an attribute value (e.g. <tag attribute="<b>hi</b>"></tag>
). According to this, it seems that this should be done by default on string attribute types, however I get the invalid character error. Is there a way to make XAttribute treat it as CDATA?
Asked
Active
Viewed 375 times
0
1 Answers
0
You cannot specify XML attribute values as CDATA. What you can do you can escape the xml you want to place as a value:
<tag attribute="<b>hi</b>"></tag>
will become
<tag attribute="<b>hi</b>"></tag>
If you are building a document and you want to add this attribute all you need to do is to add html in XAttribute constructor:
var doc = new XDocument(new XElement("tag", new XAttribute("attribute", "<b>hi</b>")));
To get the value as an xml document you can use this code:
var doc = XDocument.Parse("<tag attribute=\"<b>hi</b>\"></tag>");
var attributeValue = doc.Root.Attribute("attribute").Value;
var newDoc = XDocument.Parse(attributeValue);

Damian
- 2,752
- 1
- 29
- 28
-
thanks @Damian, I know about escaping html tags. However, I was referring to the XML spec in the post where it seems that you need not escape any tags for an attribute since it's by default treated as CDATA. I was just wondering if there was a way to get XElement to recognize this. – Riz Jan 09 '17 at 22:06