使用 Java DOM + Transformer 时省略 xml 声明中的 standalone 属性。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1682796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Omitting the standalone attribute in xml declaration when using Java DOM + Transformer.
提问by vicsz
Is there any way to tell the Transformer (when serializing an XML document using DOM), to omit the standalone attribute?
有什么方法可以告诉转换器(使用 DOM 序列化 XML 文档时)省略独立属性?
Preferably without using a hack, i.e. ommitting the whole XML declaration and then prepending it manually.
最好不使用 hack,即省略整个 XML 声明,然后手动添加它。
My current code:
我目前的代码:
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();
Current:
当前的:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<someElement/>
Intended:
故意的:
<?xml version="1.0" encoding="UTF-8">
<someElement/>
回答by vicsz
Figured it out..
弄清楚了..
Instead of changes to the transformer,
而不是改变变压器,
I add the following to the document object.
我将以下内容添加到文档对象中。
document.setXmlStandalone(true);
回答by HymanBauer
document.setXmlStandalone(true/false);is working OK.
document.setXmlStandalone(true/false);工作正常。
回答by Rod Lima
You have to use a combination of:
您必须使用以下组合:
doc.setXmlStandalone(true);
doc.setXmlStandalone(true);
and
和
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // this is used to show the standalone tag
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // this is used to show the standalone tag
回答by jarnbjo
Which Java version are you using and/or which XSLT transformer? With Sun Java 1.6.0_16, the standalone attribute is only set in the output document if you set the output property and the content is also correct.
您使用的是哪个 Java 版本和/或哪个 XSLT 转换器?在 Sun Java 1.6.0_16 中,仅当您设置了 output 属性并且内容也正确时,才在输出文档中设置了 standalone 属性。

