Transform输出xml并且更改版本为1.1

【Transform输出xml并且更改版本为1.1】简介
java jdk绑定的jar库以为版本很老,所以不支持生成xml version1.1,所以为了解决这个问题我们需要引入 xalan-2.7.2包,Jdk测试版本jdk1.8.0_40-b26,具体可参考官方文档
gradle引入:

compile ('xalan:xalan:2.7.2')

测试代码
@Test public void smlVersionTest() throws TransformerException, ParserConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); Document doc = createResponseDocument(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("xmlVerTest.xsd")); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // 更改版本,xml默认为1.0 transformer.setOutputProperty(OutputKeys.VERSION, "1.1"); transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2"); transformer.transform(source, result); }private Document createResponseDocument() throws ParserConfigurationException { DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbfactory.newDocumentBuilder(); Document responseDocument = builder.newDocument(); Element rootElement = responseDocument.createElement("root"); responseDocument.appendChild(rootElement); Element statusMessageElement = responseDocument.createElement("statusMessage"); rootElement.appendChild(statusMessageElement); Element requestElement = responseDocument.createElement("request"); rootElement.appendChild(requestElement); Map requestParameter = new HashMap<>(); requestParameter.put("xmlVer", "1.1"); return responseDocument; }


    推荐阅读