2017-01-10 5 views
1

私はXMLファイルを持っています。これは、フォルダに格納されているXSSとXSLを使用してXMLを適切な形式で表示します。 私は次のコードJEditorPaneにスタイルシートを含む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

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

はあなたの特定のxsltxml文書のための適切なInputStreamまたはStreamSourceを使用してください。

+0

ありがとうございました。 – sam

関連する問題