xml+xsl轉換為html

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.