2017-01-10 29 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); 

使用適當的InputStreamStreamSource爲特定xsltxml文件。

+0

謝謝:)幫了很多 – sam