如何通过XSLT在输出中添加<![CDATA[ ]]>?技术求助
Hey there! Let's sort out this CDATA issue you're facing. The problem with your current code is that you're passing a variable name (URL1) to cdata-section-elements—but this attribute expects the name of an XML element in your final output, not a variable.
Here are two reliable ways to get your URL wrapped in CDATA as you want:
Method 1: Use xsl:output to Auto-Generate CDATA (Recommended)
This is the cleanest, standards-compliant approach. Tell the XSLT processor to wrap the content of your target url element in CDATA directly via the output settings:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Instruct the processor to wrap <url> element content in CDATA --> <xsl:output method="xml" cdata-section-elements="url" indent="yes"/> <xsl:template match="/xml"> <url> <!-- Just output the URL content; the processor handles CDATA wrapping --> <xsl:value-of select="url"/> </url> </xsl:template> </xsl:stylesheet>
How this works:
When you set cdata-section-elements="url", the XSLT processor automatically wraps the text content of any output <url> element in CDATA if it contains characters that would normally need escaping (like &, [, etc.)—exactly what your URL has.
Method 2: Manually Generate CDATA (For Fine-Grained Control)
If you need to conditionally wrap content in CDATA (or if your processor has edge-case issues with the first method), you can manually output the CDATA tags with disabled escaping:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/xml"> <url> <!-- Output CDATA start tag (disable escaping so it isn't converted to entities) --> <xsl:text disable-output-escaping="yes"><![CDATA[</xsl:text> <!-- Insert the URL content --> <xsl:value-of select="url"/> <!-- Output CDATA end tag --> <xsl:text disable-output-escaping="yes">]]></xsl:text> </url> </xsl:template> </xsl:stylesheet>
Note:
disable-output-escaping is supported by most major XSLT processors (like Saxon, Xalan), but it's not part of the strict XSLT 1.0 standard—so use this only if the first method doesn't fit your needs.
Either of these approaches will produce your desired output:
<url><![CDATA[https://example.com?adults=1&av-seleccion-grupo=on&babies=0&children=0&dateFrom[0]]]></url>
内容的提问来源于stack exchange,提问作者Venkat

