Java 转换器错误 : Could not compile stylesheet

标签 java xml xslt

我想用 Java 中的 XSLT 转换 XML。为此,我使用了 javax.xml.transform 包。但是,我得到异常 javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet。这是我正在使用的代码:

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();
}

请注意,我标记了引发异常的行。

当我进入方法时,XSLTRule 的值是这样的:

<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>

最佳答案

constructor

public StreamSource(String systemId)

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

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

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

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

关于Java 转换器错误 : Could not compile stylesheet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5472298/

相关文章:

java - 在二维数组中随机生成簇

android - 您应用的 AndroidManifest.xml 中的必需元数据标记不存在。

xml - 如何将所有 xml 节点与 cdata-section-elements 匹配

xml - 复制带有属性的 xml 文档

c++ - C++ 中 <Pointer, String> 的 unordered_map

xml - 将 Excel 电子表格导出到 XML 并在导出期间或之后按字母顺序对数组进行排序?

java - 在 Clojure/Java 中检测 Unicode 文本连字

java - 为什么要加40左右?

java - 如果唯一标识符位于同级元素中,则用于单击链接的 xpath 表达式

android - 需要让我的android应用程序修改服务器上的xml文件,修改后需要保存更改