XSL-使具有命名空间的所有节点值在CDATA部分中可用

时间:2018-12-18 22:42:05

标签: xslt

我正在寻找XSL将提供的输入转换为预期的输出。我刚刚提供了示例,但实际的输入xml具有1000多个节点,并且由于太多的节点无法使用XSL中的CDATA部分,请您帮忙。

输入:

<note>
   <to>Tove</to>
   <from>Jani</from>
   <heading>Reminder</heading>
   <body>Don't forget me this weekend!</body>
</note>

输出:

<note>
   <to><![CDATA[Tove]]></to>
   <from><![CDATA[Jani]]></from>
   <heading><![CDATA[Reminder]]></heading>
   <body><![CDATA[Don't forget me this weekend!]]></body>
</note>

1 个答案:

答案 0 :(得分:0)

您可以通过使用cdata-section-elements元素的xsl:output属性来实现此目的,该属性指定应在CDATA部分中输出的所有元素。

因此,请使用以下XSLT-1.0:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" version="1.0" cdata-section-elements="to from heading body" encoding="UTF-8" indent="yes" omit-xml-declaration="yes" />

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

</xsl:stylesheet>

请参见cdata-section-elements表示元素to from heading body,将其内容包含在CDATA节中。 身份模板只是复制与此相关的所有文件。


如果元素位于名称空间中,则必须在cdata-section-elements中用适当的名称空间前缀为元素名称加上前缀。

例如,如果您在根元素上具有以下带有命名空间的XML,则所有子节点也都在该命名空间中。

<?xml version="1.0" encoding="utf-8"?>
<Bank xmlns="http://xxyy.x.com" Operation="Create">
  <Customer type="random">
    <CustomerId>Id10</CustomerId>
    <CountryCode>CountryCode19</CountryCode>
    <LanguageCode>LanguageCode20</LanguageCode>
    <AddressArray>
      <Address type="primary">
        <StreetAddress>179 Alfred St</StreetAddress>
        <City>Fortitude Valley</City>
        <County>GR</County>
        <Country>India</Country>
      </Address>
    </AddressArray>
  </Customer>
</Bank>

使用此XSLT(请注意xsl:stylesheet元素上的名称空间声明):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ns0="http://xxyy.x.com">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" cdata-section-elements="ns0:CustomerId ns0:CountryCode ns0:LanguageCode ns0:StreetAddress ns0:City ns0:County ns0:Country" omit-xml-declaration="yes" />

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

</xsl:stylesheet>
相关问题