Search code examples
javaxmlxml-serialization

remove xml declaration from the generated xml document using java


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


Solution

  • Have you seen OutputKeys as used by Transformer? Specifically OMIT_XML_DECLARATION.

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