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

时间:2015-05-18 15:56:44

标签: java xslt-2.0 saxon

我正在尝试将java代码中的字节数组作为参数发送到xslt。我在XSL中将类型声明为base64Binary,并将字节数组设置为参数。我收到一个错误,提供的值是字节。我做错了什么?

XSL: -

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

Java代码: -

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

错误代码: XPTY0004:变量值的必需项类型是xs:base64Binary;提供的值具有项类型xs:byte

2 个答案:

答案 0 :(得分:1)

XSLT正在等待base64binary,但您提供byte如果您不介意,只需更改:

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

通过

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

如果你想支持base64binary检查this answer,它显示了如何从byte[]转换为base64binary,基本上是:

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

答案 1 :(得分:0)

我无法重现这个问题。以下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();
        }
    }

以上的输出是

<out>U0FNUExF</out>