How to suppress the xml element added by Transformer of javax.xml.transform.Transformer

StackOverflow https://stackoverflow.com/questions/7718169

  •  08-02-2021
  •  | 
  •  

Pregunta

I've been using the Java APIs to parse an XML file so I could add, remove, or update elements/attributes. Everything works the way I want, except that the Transformer object I'm using adds <?xml version="1.0" encoding="UTF-8"?> to the beginning of the XML file. I was wondering if there is a way to suppress this.

P.S. I also noticed that this top-voted answer mentioned that we might be able to supress it.

DOMSource source = new DOMSource(document);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
FileOutputStream fout = new FileOutputStream(new File(outputFile));            
StreamResult result = new StreamResult(fout);
transformer.transform(source, result);
fout.close();

The original document does not contain <?xml version="1.0" encoding="UTF-8"?>

¿Fue útil?

Solución

If you can change the XSLT, then just add

<xsl:output omit-xml-declaration="yes"/>

or if you already have an <xsl:output.../> element in the stylesheet, just add the omit-xml-declaration="yes" attribute value.

If you can't change the XML, then depending on the specific transformer's serializer implementation, you may be able to set a parameter or feature to disable the XML declaration. Technically this is an option to the output serializer, not the transformer per se, and some implementations allow you to pass parameters to the serializer. How you actually accomplish this depends on the implementation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top