我正在尝试从 java 转换器创建 html 5 输出。我有
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> ,我不知道如何获得它。查看关于 Transformer 的文档,我只看到如何打开或关闭 header 的 xml 版本。
正如您在我的代码中看到的,我尝试将输出键方法设置为 html,并且我尝试实现建议的 here但生成的 html 文件仍然没有 doc 类型行。
我考虑过的另一个选择是创建一个 doctype 元素,但我不知道如何将它与我的 html 元素关联起来。
最佳答案
在第 5 行添加类似的内容:
DOMImplementation domImpl = doc.getImplementation();
DocumentType doctype = domImpl.createDocumentType("");
doc.appendChild(doctype);
这将添加空的 DocType(通常与 HTML5 一起使用)。
关于java 用 doctype 转换为 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30063684/