Percent-encoding using XSLT

2019-09-11 04:30发布

问题:

I have the following xml in which the value of <prvNum> has some special characters.

 <?xml version="1.0" encoding="UTF-8"?>
<root>
   <prvNum>SPECIAL#1&amp;</prvNum>
</root>

Now I want to perform percent-encoding for the value of <prvNum>. For example the value should be changed as below after percent encoding:

SPECIAL%231%26

I am trying with the following code snippet, but couldn't achieve the desired percent-encoding:

encode-uri(<xsl:value-of select="normalize-space(//prvNum)"/>)

My complete XSLT is below:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="/">
      <Request>
         <xsl:apply-templates select="//root" />
      </Request>
   </xsl:template>
   <xsl:template match="Request">
      <requestSpecific>
         <xsl:value-of select="normalize-space(//prvNum)" />
      </requestSpecific>
   </xsl:template>
</xsl:stylesheet>

Can anybody tell me where I am doing the mistake?

回答1:

Here I am just implementing the application of the XPath 2.0 function encode-for-uri suggested by TimC. So the XSLT 2.0 should look like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

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

   <xsl:template match="prvNum">
      <prvNum>
        <xsl:copy-of select="@*" />
        <xsl:value-of select="encode-for-uri(text())" />
      </prvNum>
   </xsl:template>

</xsl:stylesheet>


标签: xslt