且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Java中的DOM解析器在XML文件中声明doctype,xml版本和编码?

更新时间:2023-11-25 13:45:22

代码显示了默认行为以及更改方式:

Code showing the default behavior and the way to change that:

String inputXml = "<root><value>Test</value></root>";

// Build DOM tree for input XML
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document document = domBuilder.parse(new InputSource(new StringReader(inputXml)));

// Print DOM XML using default settings
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(System.out));

System.out.println();   System.out.println();

// Print DOM XML using specific settings
document.setXmlVersion("1.1");
transformer.setOutputProperty(OutputKeys.ENCODING, "windows-1252");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "ROOT-VALUE");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "RootValue.dtd");
transformer.transform(new DOMSource(document), new StreamResult(System.out));

Output (使用Java 1.8.0_51)

Output (using Java 1.8.0_51)

<?xml version="1.0" encoding="UTF-8" standalone="no"?><root><value>Test</value></root>

<?xml version="1.1" encoding="windows-1252" standalone="no"?><!DOCTYPE root PUBLIC "ROOT-VALUE" "RootValue.dtd">
<root><value>Test</value></root>