2008-09-12 102 views
33

是否有一種簡單的方法來將HTML轉換爲帶有JAVA的markdown?HTML到Markdown與Java

我目前使用Java MarkdownJ庫將markdown轉換爲html。

import com.petebevin.markdown.MarkdownProcessor; 
... 
public static String getHTML(String markdown) { 
    MarkdownProcessor markdown_processor = new MarkdownProcessor(); 
    return markdown_processor.markdown(markdown); 
} 

public static String getMarkdown(String html) { 
/* TODO Ask stackoverflow */ 
} 

回答

38

使用此XSLT

如果需要使用XSLT幫助和Java這裏的代碼片段:

public static void main(String[] args) throws Exception { 

     File xsltFile = new File("mardownXSLT.xslt"); 

     Source xmlSource = new StreamSource(new StringReader(theHTML)); 
     Source xsltSource = new StreamSource(xsltFile); 

     TransformerFactory transFact = 
       TransformerFactory.newInstance(); 
     Transformer trans = transFact.newTransformer(xsltSource); 

     StringWriter result = new StringWriter(); 
     trans.transform(xmlSource, new StreamResult(result)); 
    } 
+2

+1,這太棒了。 – 2010-09-06 21:49:13

2

我工作的同樣的問題,並與一對夫婦不同的技術試驗。

上面的答案可以工作。您可以使用jTidy library執行初始清理工作並將其從HTML轉換爲XHTML。您使用上面鏈接的XSLT stylesheet

不幸的是,沒有一個庫有一個一站式的功能,可以在Java中執行此操作。您可以嘗試使用Python腳本html2text和Jython,但我還沒有嘗試過!

1

如果您正在使用大規模殺傷性武器的編輯,並希望得到在服務器端降價的代碼,只需使用加載wmd.js腳本之前這些選項:

wmd_options = { 
     // format sent to the server. can also be "HTML" 
     output: "Markdown", 

     // line wrapping length for lists, blockquotes, etc. 
     lineLength: 40, 

     // toolbar buttons. Undo and redo get appended automatically. 
     buttons: "bold italic | link blockquote code image | ol ul heading hr", 

     // option to automatically add WMD to the first textarea found. 
     autostart: true 
    };