Java Transformer错误:无法编译样式表 [英] Java Transformer error: Could not compile stylesheet

查看:865
本文介绍了Java Transformer错误:无法编译样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java中的XSLT转换XML。为此,我使用 javax.xml.transform 包。但是,我得到异常 javax.xml.transform.TransformerConfigurationException:无法编译样式表。这是我正在使用的代码:

I'm want to transform a XML with XSLT in Java. For that I'm using the javax.xml.transform package. However, I get the exception javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet. This is the code I'm using:

public static String transform(String XML, String XSLTRule) throws TransformerException {

    Source xmlInput = new StreamSource(XML);
    Source xslInput = new StreamSource(XSLTRule);

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xslInput); // this is the line that throws the exception

    Result result = new StreamResult();
    transformer.transform(xmlInput, result);

    return result.toString();
}

请注意,我标记了抛出异常的行。

Note that I marked the line which throws the exception.

当我输入方法时, XSLTRule 的值为:

When I enter the method, the value of XSLTRule is this:

<xsl:stylesheet version='1.0'
 xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
 xmlns:msxsl='urn:schemas-microsoft-com:xslt'
 exclude-result-prefixes='msxsl'
 xmlns:ns='http://www.ibm.com/wsla'>
    <xsl:strip-space elements='*'/>
    <xsl:output method='xml' indent='yes'/>
    <xsl:template match='@* | node()'>
        <xsl:copy>
            <xsl:apply-templates select='@* | node()'/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="/ns:SLA
                            /ns:ServiceDefinition
                               /ns:WSDLSOAPOperation
                                  /ns:SLAParameter[@name='Performance']"/>
</xsl:stylesheet>


推荐答案

构造函数

public StreamSource(String systemId)

从URL构造StreamSource。我认为你正在传递XSLT的内容。试试这个:

Construct a StreamSource from a URL. I think you're passing the content of the XSLT instead. Try this:

File xslFile = new File("path/to/your/xslt");
TransformerFactory factory = TransformerFactory.newInstance();
Templates xsl = factory.newTemplates(new StreamSource(xslFile));

你还必须设置 OutputStream 你的 StreamResult 将写入:

You must also set the OutputStream that your StreamResult will write to:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();

这篇关于Java Transformer错误:无法编译样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆