【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;
}
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)