Convert 'embedded' XML doc into CDATA output in XSLT (1.0)

主宰稳场 提交于 2019-12-06 04:32:17

There are two confusions you need to clear up here.

First, you probably want xsl:copy-of rather than xsl:value-of. The latter returns the string value of an element, the former returns a copy of the element.

Second, the cdata-section-elements attribute on xsl:output affects the serialization of text nodes, but not of elements and attributes. One way to get what you want would be to serialize the HTML yourself, along the lines of the following (not tested):

<xsl:template match="document/descendant::*">
  <xsl:value-of select="concat('&lt;', name())"/>
  <!--* attributes are left as an exercise for the reader ... *-->
  <xsl:text>&gt;</xsl:text>
  <xsl:apply-templates/>
  <xsl:value-of select="concat('&lt;/', name(), '>')"/>
</xsl:template>

But the quicker way would be something like the following solution (squeamish readers, stop reading now), pointed out to me by my friend Tommie Usdin. Drop the cdata-section-elements attribute from xsl:output and replace your template for the document element with:

<xsl:template match="document">
  <document>
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text>
    <xsl:copy-of select="./html"/>
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text>
  </document>
</xsl:template> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!