在JEditorPane中使用样式表显示XML

时间:2017-01-10 10:08:45

标签: java xml swing xslt 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的文本部分,没有任何样式。我该怎么做才能用样式表进行显示。

1 个答案:

答案 0 :(得分:1)

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);

为您的特定InputStreamStreamSource文件使用适当的xsltxml