Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding HTML to an XElement

Tags:

c#

xml

linq

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?

like image 871
dkarzon Avatar asked Oct 27 '25 06:10

dkarzon


2 Answers

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>
like image 189
Sven Avatar answered Oct 29 '25 05:10

Sven


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);
  }
}
like image 27
Serj-Tm Avatar answered Oct 29 '25 07:10

Serj-Tm