xml标签自闭合会改变报文格式,在一些涉及加密的程序处理中,自闭合导致报文更改从而引起非实际内容篡改所导致的加解密不一致的情况。以下程序是将自闭和更改为结束标签
package com.parse.xml;
import java.io.StringWriter;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class FormatXml {
public static void fotmatXml(String xmlMsg) {
OutputFormat format=new OutputFormat();
format.setEncoding("UTF-8");
//关闭自闭合标签
format.setExpandEmptyElements(true);
StringWriter strWtr=new StringWriter();
try {
XMLWriter xmlWrt=new XMLWriter(strWtr,format);
xmlWrt.write(DocumentHelper.parseText(xmlMsg));
xmlWrt.flush();
xmlWrt.close();
} catch (Exception e) {
e.printStackTrace();
}
//格式化,去掉换行
String formatXml = strWtr.toString().replaceAll("\r|\n", "");
System.out.println(formatXml);
}
public static void main(String[] args) {
String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><name>张三</name><age/></note>";
String xml1="<note><name>张三</name><age/></note>";
fotmatXml(xml);
fotmatXml(xml1);
}
}
需要注意的是报文传输中一般是一个无换行的字符串,所以需要格式化去掉换行,
执行结果:
<?xml version="1.0" encoding="UTF-8"?><note><name>张三</name><age></age></note>
<?xml version="1.0" encoding="UTF-8"?><note><name>张三</name><age></age></note>
可以看到即使不声明,结果会默认版本极编码