Summary: I'm using xslt to convert data, and need to produce some tags with CDATA inside and some tags without. Is escaping the CDATA sections my only option?
I'm attempting to convert data I already have in xml to Moodle Xml for importing. The final product needs to include some Html, which the Moodle Xml doc specifically says needs to be contained in CDATA.
Desired Output:
<question>
<name>
<text>FooName</text>
</name>
<questiontext format="html">
<text><![CDATA[<img src="1.png">]]></text>
</questiontext>
</question>
I gave this a try using the following code (trimmed down, but will include the data from my input xml file):
Method 1, nothing special
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/">
<question>
<name>
<text>FooName</text>
</name>
<questiontext format="html">
<text><![CDATA[<img src="1.png">]]></text>
</questiontext>
</xsl:template>
</xsl:stylesheet>
And got...
Bad Output from Method 1
<question>
<name>
<text>FooName</text>
</name>
<questiontext format="html">
<text><img src="1.png"></text>
</questiontext>
</question>
So I look up the xslt documentation and some SO questions, which seem to say I have 2 options:
- Do nothing, CDATA gets escaped.
- use
cdata-section-elements ="text"
to auto-generate cdata sections inside tags - Generate CDATA sections by hand, using
disable-output-escaping="yes"
Ok, autogeneration sounds good. Lets try that:
Method 2 adding cdata-section-elements="text"
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" cdata-section-elements="text"/>
Bad Output from cdata-section-elements ="text"
:
<question>
<name>
<text><![CDATA[FooName]]></text>
</name>
<questiontext format="html">
<text><![CDATA[<img src="1.png">]]></text>
</questiontext>
</question>
So 2 isn't an option because there are other elements I do NOT want containing CDATA, in a schema I don't control.
This leaves me with option 3, escaping it by hand. My question then is: Is option 3 my only option? Is there anything else I can do to get my desired output using XSLT? not using XSLT?