0

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?

Community
  • 1
  • 1
Riz
  • 6,486
  • 19
  • 66
  • 106

1 Answers1

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="&lt;b&gt;hi&lt;/b&gt;"></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=\"&lt;b&gt;hi&lt;/b&gt;\"></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