How to convert XML with CDATA to HTML and back again?
I'm receiving XML data via AJAX and the XML includes some CDATA values. The XML needs to be added to the page and then later scraped from the page and sent back as XML via AJAX.
Simple Example:
I receive -
<MyXML>
<MyTag>
<![CDATA[Hello World]]>
</MyTag>
</MyXML>
and want to end up with:
<HTML>
<Body>
<MyXML>
<MyTag>
Hello World
</MyTag>
</MyXML>
</Body>
</HTML>
and then send back as XML
<MyXML>
<MyTag>
<![CDATA[Hello World - Hey I've been edited!]]>
</MyTag>
</MyXML>
99% of this is easy except the handling of the CDATA tag.
If I treat the XML as HTML, the CDATA tags get commented out automatically by JQuery. So .html() returns <!--<![CDATA[Hello World]]>--> and .text() returns an null value (which is correct for a node containing only a comment).
If I treat the XML as XML, then .html() doesn't work making it impossible to insert the data (with its XML tags) into my page.
The only way around this I can see is to create a function that loops through the XML creating a HTML duplicate somehow and converting the CDATA nodes. When I want to send it back I have to reverse the process.
This seems a very long winded process when all I want to do is treat the XML as HTML except for the CDATA which needs to converted appropriately.
So two questions:
1) Am I missing some easy way to do all this using JQuery or other tools?
2) If I do need to manually convert the XML into HTML and vice versa, how do I do it?