Search code examples
xmlparsingcdata

CDATA to ignore html tags doesn't work


Hi I'm passing a message to an attribute in XML. The xml is 'emailBodyXML' and the attribute I want to receive the message is the 'body'. The message I'm passing is contained in a variable 'emailBody'.

I have this code:

emailBodyXML.selectSingleNode("//email").setAttribute("body", "<![CDATA[" + emailBody + "]]>");

I put cdata in it because I want it to ignore the html tags the emailBody may contain. But when I debug it, the html tags get converted to &lt; or &gt;. I don't like it to get converted to that. I want it to still show '<' and '>'. What's wrong with my code?


Solution

  • You can't have < in an attribute value, so your <![CDATA[... is invalid. You aren't going to be able to put markup in a attribute value without using entities for < (and quotes, ampersands, etc.). Your best bet would be to use CDATA in an element instead.

    http://www.w3.org/TR/2008/REC-xml-20081126/#attdecls

    Example:

    <body><![CDATA[<p>HTML MARKUP GOES HERE.</p>]]></body>