Im using the classes in System.Linq.Xml to build up an XML object. But the API I am working with require me to put straight HTML code into a tag:
<message><html><body>...</body></html></message>
I cant seem to figure out how to do this using XElement.
new XElement("message", myHtmlStringVariable);
That just escapes all the HTML characters
new XElement("message", new XCData(myHtmlStringVariable));
That wraps the HTML in a <![CDATA[…]]> which the API doesnt like.
So is there a way to insert HTML directly into an XElement’s content?
You can do this:
This does require that the HTML is well-formed XML and has only a single root element.
If you have an HTML snippet with multiple root elements, you can always create the element like this:
The requirement for well-formed XML still exists. This means you must have empty elements like
<br />and not<br>. There is no way around that if you want to embed HTML directly in XML.Additionally, if it’s possible and your API accepts it, I would recommend giving the HTML elements the proper XHTML namespace:
This produces XML like this: