2015-05-05 86 views
1

我想從java變壓器創建一個html 5輸出。我有java轉換爲html與doctype

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 

Document doc = docBuilder.newDocument(); 

Element html= doc.createElement("html"); 
.... //populate the html element 

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 

DOMSource domSource = new DOMSource(html); 
StreamResult result = new StreamResult(new File(fileLocation)); 
transformer.setOutputProperty(OutputKeys.METHOD, "html"); 
transformer.transform(domSource, result); 

這很好,併爲我創建html文件,因爲我想。但它沒有<!DOCTYPE html>在頂部,我不知道如何得到它。查看轉換器上的文檔我只看到如何打開或關閉標題的xml版本。

正如您在我的代碼中看到的,我嘗試將輸出鍵方法設置爲html,並試圖實現建議的內容here,但生成的html文件仍然沒有文檔類型行。

我已經思考的另一個選擇是創建一個doctype元素,但我不知道如何將它與我的html元素相關聯。

+0

Java封裝的XSLT 1.0轉換引擎的html輸出在超過十年之前早於HTML5。 –

+0

我很害怕這樣的事 –

+0

這並不是不可能,只是更困難和最有可能的實現依賴。 –

回答

2

添加像這樣5號線:

DOMImplementation domImpl = doc.getImplementation(); 
DocumentType doctype = domImpl.createDocumentType(""); 
doc.appendChild(doctype); 

這將增加空的DocType(如通常與HTML5使用)。