How do I force xslt transformation to load data into cdata sections?

旧时模样 提交于 2019-12-04 04:00:58

问题


I have a client who requires all text in the xml I supply them with to be in CDATA sections. I understand that text should not need to be in CDATA as it has already been parsed and transformed when it is supplied to the client. However, no matter how sure I am, they still need the CDATA sections. Sigh.

I am processing my data with Saxon 9.3, using the command line transform command.


回答1:


Well as your question title talks about XSLT and your question is flagged as XSLT, the XSLT way to ensure a result element's content is serialized as a CDATA section is to use the cdata-section-elements attribute on the xsl:output element (http://www.w3.org/TR/xslt20/#serialization) listing all elements you want to output as CDATA sections. Thus if you know the elements you want to output as CDATA sections when writing the stylesheet it is a simple as listing them in that attribute. Does that help? Or do you want to postprocess arbitrary XML with XSLT to add CDATA sections?




回答2:


Here is a complete example:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"
 cdata-section-elements="num"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following sample XML document:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

the result has all text nodes (all of them are children of num elements) represented within CDATA sections:

<nums>
   <num><![CDATA[01]]></num>
   <num><![CDATA[02]]></num>
   <num><![CDATA[03]]></num>
   <num><![CDATA[04]]></num>
   <num><![CDATA[05]]></num>
   <num><![CDATA[06]]></num>
   <num><![CDATA[07]]></num>
   <num><![CDATA[08]]></num>
   <num><![CDATA[09]]></num>
   <num><![CDATA[10]]></num>
</nums>

Explanation:

  1. Using the identity rule to output every node as is.

  2. Using the cdata-section-elements attribute of xsl:output to specify the space-separated list of elements, whose text-node children must be serialized as CDATA sections.

Do note: In your case it would be convenient not to modify your existing transformations at all, but to have a post-processing step on their results that is similar to this example.



来源:https://stackoverflow.com/questions/9465560/how-do-i-force-xslt-transformation-to-load-data-into-cdata-sections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!