简体   繁体   English

Java在XSL转换中将byte []发送到base64Binary

[英]Java send byte[] to base64Binary in XSL transformation

I'm trying to send a byte array from java code as a parameter to xslt. 我正在尝试从Java代码发送字节数组作为xslt的参数。 I declared the type as base64Binary in XSL and set the byte array as parameter. 我在XSL中将类型声明为base64Binary,并将字节数组设置为参数。 I get an error that the supplied value is byte. 我收到一个错误,提供的值为字节。 What am I doing wrong? 我究竟做错了什么?

XSL:- XSL: -

<xsl:param name="attachmentBytes" as="xs:base64Binary" />

Java code:- Java代码:

byte[] bytes = "SAMPLE".getBytes();
transformer.setParameter("attachmentBytes", bytes);
transformer.transform(new DOMSource(sourceDocument), new StreamResult(targetStream));

Error code: XPTY0004: Required item type of value of variable is xs:base64Binary; 错误代码: XPTY0004:变量值的必需项目类型为xs:base64Binary; supplied value has item type xs:byte 提供的值的项目类型为xs:byte

XSLT is waiting for a base64binary but you're giving a byte , if you dont mind the type , just change: XSLT正在等待base64binary但您要提供一个byte如果您不介意类型 ,则只需更改:

<xsl:param name="attachmentBytes" as="xs:base64Binary" />

by 通过

<xsl:param name="attachmentBytes" as="xs:byte" />

If you want to mantain the base64binary check this answer that shows how to convert from byte[] to base64binary , basically: 如果要保留base64binary,请检查以下答案该答案显示了如何从byte[]转换为base64binary ,基本上是:

StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();

I'm unable to reproduce the problem. 我无法重现该问题。 The following JUnit test completes successfully: 以下JUnit测试成功完成:

public void testBase64BinaryParam() {
        try {
            String xsl = "<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" +
                " <xsl:param name='in' as='xs:base64Binary' xmlns:xs='http://www.w3.org/2001/XMLSchema'/>\n" +
                " <xsl:template match='/'>\n" +
                "   <out><xsl:value-of select='string($in)'/></out>\n" +
                " </xsl:template> \n" +
                "</xsl:stylesheet>";
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer transformer =
                tfactory.newTransformer(new StreamSource(new StringReader(xsl)));
            byte[] bytes = "SAMPLE".getBytes();
            transformer.setParameter("in", new net.sf.saxon.value.Base64BinaryValue(bytes));
            transformer.setOutputProperty("omit-xml-declaration", "yes");
            transformer.transform(new StreamSource(new StringReader(xsl)),
                new StreamResult(System.out));
        } catch (Exception err) {
            fail();
        }
    }

The output of the above is 上面的输出是

<out>U0FNUExF</out>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM