xslt 1.0 base64 encode the content of a template

2020-02-07 03:53发布

问题:

How can I encode the content of a template in base64, using XSLT 1.0?

Edit: using serialization mode, runing in PHP enviroment

It's like i have a template like this:

<xsl:template name="test">
    <test 
      gender="male" 
      name1="TEST" 
      name2="TEST">
      <sometags>
            <tag></tag>
        </sometags>
    </test>
</xsl:template>

and I want the output to be like this:

<base64>PHRlc3QgDQoJCSAgZ2VuZGVyPSJtYWxlIiANCgkJICBuYW1lMT0iVEVTVCIgDQoJCSAgbmFtZTI9IlRFU1QiPg0KICAgICAgICAgIDxzb21ldGFncz4NCgkJCQk8dGFnPjwvdGFnPg0KCQkJPC9zb21ldGFncz4NCgkJPC90ZXN0Pg==</base64>

回答1:

Mukhul Gandhi created a Base64 encoder that runs in XSLT 1.0. If you can switch to XSLT 2.0, you can create stylesheet functions to do the same.

However, because you seem to mean to encode nodes into strings, you should not create nodes, but strings instead:

Re-apply the result of your template using the node-set extension function (supported by (almost?) all XSLT 1.0 processors) and write something like this:

<xsl:template match="*">
    <xsl:text>&lt;</xsl:text>
    <xsl:value-of select="name()" />
    <xsl:apply-templates select="@*" />
    <xsl:text>&gt;</xsl:text>
    <xsl:apply-templates />
    <xsl:text>&lt;/</xsl:text>
    <xsl:value-of select="name()" />
    <xsl:text>&gt;</xsl:text>
</xsl:template>

<xsl:template match="@*">
    <xsl:text> </xsl:text>
    <xsl:value-of select="name()" />
    <xsl:text>="</xsl:text>
    <xsl:value-of select="." />
    <xsl:text>"</xsl:text>
</xsl:template>

Note: not tested, and you probably want to extend it to add indentation, processing of other nodes like processing instructions and comments, and in the case of attributes, to escape any quotes in the strings.

In XSLT 3.0 you can achieve the same using the fn:serialize function.