score:10

Accepted answer

You can do this:

string html = "<html><body></body></html>";
XElement message = new XElement("message", XElement.Parse(html));

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:

string html = "<p>foo</p><p>bar</p>";
XElement message = XElement.Parse("<message>" + html + "</message>");

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:

string html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><body></body></html>";
XElement message = new XElement("message", XElement.Parse(html));

This produces XML like this:

<message>
  <html xmlns="http://www.w3.org/1999/xhtml">
    <body></body>
  </html>
</message>

score:3

new XElement("message", new XRaw(myHtmlStringVariable));

public class XRaw : XText
{
  public XRaw(string text):base(text){}
  public XRaw(XText text): base(text){}

  public override void WriteTo(System.Xml.XmlWriter writer)
  {
    writer.WriteRaw(this.Value);
  }
}

Related Query

More Query from same tag