Problem Description
Summary: I'm using xslt to convert data, and need to produce some <text> tags with CDATA inside and some <text> tags without. Is escaping the CDATA sections my only option?
I'm attempting to convert data I already have in xml to [Moodle Xml][1] for importing. The final product needs to include some Html, which the [Moodle Xml doc][2] 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>&lt;img src="1.png"&gt;</text>
</questiontext>
</question>
So I look up the [xslt documentation][3] and [some SO questions][4], which seem to say I have 2 options:
1. Do nothing, CDATA gets escaped.
2. use `cdata-section-elements ="text"` to auto-generate cdata sections inside <text> tags
3. 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 <text> elements I do NOT want containing...
AI-Generated Solution
Powered by LMSouq AI · GPT-4.1-mini
Analyzing problem and generating solution…
Was this solution helpful?