使用 java 从生成的 xml 文档中删除 xml 声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2133395/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:57:12  来源:igfitidea点击:

remove xml declaration from the generated xml document using java

javaxmlxml-serialization

提问by flash

String root = "RdbTunnels";
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(root);
document.appendChild(rootElement);   

OutputFormat format = new OutputFormat(document);
format.setIndenting(true);


XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(document);

gives the result as following

结果如下

<?xml version="1.0" encoding="UTF-8"?>
<RdbTunnels/>

but I need to remove the xml declaration from the output how can I do that

但我需要从输出中删除 xml 声明我该怎么做

采纳答案by Brian Agnew

Have you seen OutputKeysas used by Transformer? Specifically OMIT_XML_DECLARATION.

您是否见过Transformer使用的OutputKeys?特别是OMIT_XML_DECLARATION

Note that removing the header is valid in XML 1.0, but you lose character encoding data (amongst other things) which can be very important.

请注意,删除标头在 XML 1.0 中是有效的,但是您会丢失非常重要的字符编码数据(除其他外)。

回答by Peter Lindqvist

Add this

添加这个

format.setOmitXMLDeclaration(true);

Example

例子

OutputFormat format = new OutputFormat(document);
format.setIndenting(true);
format.setOmitXMLDeclaration(true);

回答by Remy Mellet

By using the setOmitXMLDeclaration(true); method from the Format class. I'm not sure but I think it uses jDom lib.

通过使用 setOmitXMLDeclaration(true); Format 类中的方法。我不确定,但我认为它使用 jDom 库。

Example (it will display the XML file without the XML declaration of the Document document)

示例(它将显示没有文档文档的 XML 声明的 XML 文件)

XMLOutputter out= new XMLOutputter(Format.getCompactFormat().setOmitDeclaration(true));
out.output(document, System.out);