[英]Display XML with stylesheet in JEditorPane
我有一個 XML 文件,它使用存儲在文件夾中的 XSS 和 XSL 以正確的格式顯示 XML。 當我使用以下代碼時
JEditorPane editor = new JEditorPane();
editor.setBounds(114, 65, 262, 186);
frame.getContentPane().add(editor);
editor.setContentType( "html" );
File file=new File("c:/r/testResult.xml");
editor.setPage(file.toURI().toURL());
我只能看到沒有任何樣式的 XML 的文本部分。 我應該怎么做才能使用樣式表進行顯示。
JEditorPane
不會自動處理 XSLT 樣式表。 您必須自己執行轉換:
try (InputStream xslt = getClass().getResourceAsStream("StyleSheet.xslt");
InputStream xml = getClass().getResourceAsStream("Document.xml")) {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(xml);
StringWriter output = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer(new StreamSource(xslt));
transformer.transform(new DOMSource(doc), new StreamResult(output));
String html = output.toString();
// JEditorPane doesn't like the META tag...
html = html.replace("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">", "");
editor.setContentType("text/html; charset=UTF-8");
editor.setText(html);
} catch (IOException | ParserConfigurationException | SAXException | TransformerException e) {
editor.setText("Unable to format document due to:\n\t" + e);
}
editor.setCaretPosition(0);
為您的特定xslt
和xml
文檔使用適當的InputStream
或StreamSource
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.