2012-10-29 22 views
2

我遇到了一個XSLT文件導入另一個問題的問題,導致我的應用程序拋出一個MalformedURLException。在main.xsl import語句如下:當一個XSLT導入另一個XSLT時MalformedURLException

<xsl:import href="transformCommon.xsl"/> 

文件transformCommon.xsl是在同一文件夾中main.xsl。該attemts代碼加載它看起來是這樣的:

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。有沒有人知道這個問題會出現在逐個工作站的基礎上?

回答

4

爲了能夠在樣式表(包括進口),從中創建Templates需要具有「系統ID」(即.xsl文件的URL)的Source解決相對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()); 

openStream可以拋出IOException所以你要麼需要的是添加到您的throws或包裹在整個事件中一個try/catch )。