【问题标题】:Convert string to binary base64将字符串转换为二进制base64
【发布时间】:2017-01-20 06:30:36
【问题描述】:

有什么方法可以将字符串转换为二进制 base64 吗?我看过很多参考资料,但最终都没有用。例如我有这个输入文件:

<RootElement xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <Data>
         <Binary>
               <RawData>This element should convert string to binary base64.</RawData>
         </Binary>
    </Data>
</RootElement>

我需要生成:

<RootElement xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Data>
    <Binary>
        <RawData>VGhpcyBlbGVtZW50IHNob3VsZCBjb252ZXJ0IHN0cmluZyB0byBiaW5hcnkgYmFzZTY0Lg==</RawData>
    </Binary>
</Data>

我创建了一个 xslt 并使用了我在网上看到的命名空间:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dp="http://www.datapower.com/extensions">
<xsl:output method="xml" version="1.0" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="RawData">
    <xsl:element name="RawData">
        <xsl:value-of select="dp:encode(., 'base-64')"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>

谢谢。

【问题讨论】:

  • 哪个 XSLT 处理器?仅仅包括命名空间并不能使函数可用。您还必须安装实现命名空间的库。您没有提供足够的信息让任何人回答。
  • 如果您能告诉我们您正在使用的 XSLT 处理器和 XSLT 版本,将会有所帮助。 Microsoft 的 MSXSL 扩展为您提供了一个 &lt;msxsl:script&gt; 元素,您可以使用它在 JScript/C#/etc 中定义自定义函数。对您的数据进行转换。
  • 如果您使用的是 Saxon XSLT 处理器,您可以使用特定功能,请参阅saxonica.com/html/documentation/functions/saxon/…
  • 我不认为您可以在其他处理器的其他地方使用 IBM Datapower 的扩展功能,它们是 datapower 盒子特有的。
  • 对于 Saxon 9.6 PE/EE 及更高版本,另请参阅 saxonica.com/html/documentation/functions/expath-binary/…

标签: xslt base64 xslt-1.0 xslt-2.0


【解决方案1】:

有一个纯 XSLT 1.0 解决方案适用于任何 XSLT 处理器:JAXP、Saxon、Xalan、Xsltproc、Microsoft:

  1. 下载base64.xsl
  2. 下载base64_binarydatamap.xml
  3. 使用 XSLT 1.0:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:b64="https://github.com/ilyakharlamov/xslt_base64">
        <xsl:output method="xml"/>
        <xsl:include href="base64.xsl"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:template>
        <xsl:template match="/RootElement/Data/Binary/RawData">
            <xsl:call-template name="b64:encode">
                <xsl:with-param name="asciiString" select="text()"/>
            </xsl:call-template>
        </xsl:template>
    </xsl:stylesheet>
    

【讨论】:

  • 最终的 在答案中,但在上面看不到。很好的解决方案!
猜你喜欢
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
相关资源
最近更新 更多