我遇到一个 XSLT 文件导入另一个 XSLT 文件的问题,导致我的应用程序抛出 MalformedURLException。 main.xsl
中的导入语句如下所示:
<xsl:import href="transformCommon.xsl"/>
文件 transformCommon.xsl
与 main.xsl
位于同一文件夹中。尝试加载它的代码如下所示:
private void loadXSLTFiles(String xsltFile)
{
TransformerFactory transformFactory = TransformerFactory.newInstance();
//tell the location of all of import file
transformFactory.setURIResolver(new ClassPathURIResolver());
Templates cache=null;
//cache XSLT source file for transformation reuse
InputStream is = this.getClass().getClassLoader().getResourceAsStream(xsltFile);
javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(is);
try
{
cache = transformFactory.newTemplates(xsltSource);
}
catch (TransformerConfigurationException domException)
{
LOG.logError("XSLT initialization error has occurred: " + domException.getMessage());
}
...
堆栈跟踪是:
Caused by: java.net.MalformedURLException at java.net.URL.(URL.java:602) at java.net.URL.(URL.java:465) at java.net.URL.(URL.java:414) at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source) at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source) at org.apache.xalan.templates.StylesheetRootProxy.(Unknown Source) ... 59 more
我不确定为什么会收到此错误。当我从 main.xsl
中删除导入时,一切正常。当然,删除它不是一种选择,因为这样做的全部目的是将通用功能移动到单独的 XSLT。
同样有趣的是,似乎只有我的工作站有这个问题。最初编写此代码的开发人员表示他对此没有任何问题。我正在使用 RAD 7.5。有谁知道在逐个工作站的基础上,这个问题是如何出现的?
最佳答案
为了能够解析样式表(包括导入)中的相对 URL,您从中创建 Templates
的 Source
需要有一个“系统 ID”(即 .xsl
文件的 URL)。
代替
//tell the location of all of import file
transformFactory.setURIResolver(new ClassPathURIResolver());
//cache XSLT source file for transformation reuse
InputStream is = this.getClass().getClassLoader().getResourceAsStream(xsltFile);
javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(is);
试试这个:
URL xsltURL = this.getClass().getClassLoader().getResource(xsltFile);
Source xsltSource = new StreamSource(xsltURL.openStream(),
xsltURL.toExternalForm());
/捕获)。
关于java - 当一个 XSLT 导入另一个 XSLT 时出现 MalformedURLException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13125188/