【问题标题】:How to keep/add CDATA section with XSLT on specified subnodes?如何在指定的子节点上使用 XSLT 保留/添加 CDATA 部分?
【发布时间】:2021-02-04 14:37:49
【问题描述】:

我有一个具有以下结构的 XML 文件:

<catalog>
    <category>
        <display-name>    XYZ       </display-name> 
    </category>
    <product>
        <display-name>    ABC       </display-name>
    </product>
</catalog>

如何在所有子节点目录/产品/显示名称上添加 CDATA 部分?

这是我写的那种代码,我如何在 cdata-section-elements 上选择指定的子节点:

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="no" indent="yes" cdata-section-elements="?"/>
 <xsl:strip-space elements="*"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="catalog">
  <catalog catalog-id="master-catalog">
   <xsl:apply-templates select="@*|node()"/>
  </catalog>
 </xsl:template>
</xsl:stylesheet>

感谢您的帮助!

【问题讨论】:

  • 嗯,您可以使用cdata-section-elements="display-name" 将该元素的任何文本内容序列化为 CDATA 部分。您不能让它依赖于父元素或祖先元素,它会对输出中的任何 display-name 元素执行此操作。

标签: xml xslt


【解决方案1】:

正如我在评论中所说,自 XSLT 1 以来的标准方法是列出 cdata-section-elements="display-name",尽管这将适用于结果中的任何 display-name 元素。

在 XSLT 3 中,如果您想根据匹配模式将元素序列化为 CDATA 部分,您可以对其使用 serialize 函数,然后使用 disable-output-escaping hack:

  <xsl:template match="category/display-name | product/display-name">
      <xsl:value-of select="serialize(., map { 'cdata-section-elements' : node-name() })"
                    disable-output-escaping="yes"/>
  </xsl:template>

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 2021-04-29
    • 2018-06-18
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2010-12-02
    相关资源
    最近更新 更多