有什么办法告诉Transformer(在使用DOM序列化XML文档时),忽略独立属性?使用Java DOM + Transformer时,省略xml声明中的独立属性。
最好不使用hack,即省略整个XML声明然后手动预先配置它。
我当前的代码:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //Note nothing is changed
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
return result.getWriter().toString();
电流:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<someElement/>
预期:
<?xml version="1.0" encoding="UTF-8">
<someElement/>
为什么这甚至工作?根据规范: https://www.w3.org/TR/2004/REC-xml-20040204/#sec-rmd “如果有外部标记声明但没有独立的文档声明,则值”no “ 假设。” 这个答案:https://stackoverflow.com/questions/5578645/what-does-the-standalone-directive-mean-in-xml还指出,如果缺少独立属性,则假定为“否”。那么怎么来document.setXmlStandalone(true);删除属性? – mdzh 2017-06-21 13:58:41