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:
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>
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With