標籤:xml xsl html
項目需要,需要使用xml+xsl轉換為html檔案儲存體。
以前也沒做過這樣的功能,上網搜尋到的結果基本上xml和xsl都是以檔案的形式儲存和輸入的,但我這裡已經是拿到字串了,所以考慮是否能直接使用字串。
通過閱讀對應StreamSource的代碼發現是完全可行的。
另外大部分網上的樣本都可能出現FileNotFoundException異常,還好找到瞭解決辦法。
以下為代碼:
/** * 使用xml+xsl轉換成html檔案 * @param xml xml內容字串 * @param xsl xsl內容字串 * @param htmlFilePath 目標html檔案路徑 */private void transformByXSLT(String xml,String xsl,String htmlFilePath){TransformerFactory transformerFactory = TransformerFactory.newInstance();StringReader xslReader = new StringReader(xsl);StreamSource xslSource = new StreamSource(xslReader);try {Transformer transformer = transformerFactory.newTransformer(xslSource);//設定輸出檔案的字元集transformer.setOutputProperty("encoding", "UTF-8");StringReader xmlReader = new StringReader(xml);StreamSource xmlSource = new StreamSource(xmlReader);File htmlFile = new File(htmlFilePath);//如果不使用htmlFile.toURI().getPath()的話,可能出現FileNotFoundExceptionResult result = new StreamResult(htmlFile.toURI().getPath());transformer.transform(xmlSource, result);} catch (TransformerConfigurationException e) {e.printStackTrace();} catch (TransformerException e) {e.printStackTrace();}}
htmlFile.toURI().getPath())這個寫法可以避免FileNotFoundException異常,感謝 http://blog.csdn.net/yangxiaonawzy/article/details/5806413 這篇文章。
xml+xsl轉換為html