简体   繁体   中英

Display XML with stylesheet in JEditorPane

I have an XML file, which uses an XSS and XSL stored in the folder to display the XML in a proper format. when i use the following code

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

All i can see is the text part of the XML without any styling. what should i do to make this display with style sheet.

The JEditorPane does not automatically process XSLT style-sheets. You must perform the transformation yourself:

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

Use an appropriate InputStream or StreamSource for your particular xslt and xml documents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM