9

I want to create XML in Java.

     DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder;
     docBuilder = dbfac.newDocumentBuilder();
     Document doc = docBuilder.newDocument();

but Java automatically creates declaration like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

How can I remove encoding="UTF-8" standalone="no" so it will be

<?xml version="1.0"?>

Thanks!

VextoR
  • 5,087
  • 22
  • 74
  • 109
  • possible duplicate of http://stackoverflow.com/questions/2133395/remove-xml-declaration-from-the-generated-xml-document-using-java – Umer Hayat Sep 22 '11 at 07:59
  • @JoachimSauer, I don't want to override encoding because other program uses this XML in a way I don't know. So I can't be sure what encoding I can set – VextoR Sep 22 '11 at 08:23
  • 1
    @UmerHayat, no, that question about removing ALL XML declaration – VextoR Sep 22 '11 at 08:23
  • @VextoR: **Any** tool that accepts XML **must** accept one with a valid encoding property (especially if the encoding specified is UTF-8). If your other tool doesn't accept that, then it's **broken**! – Joachim Sauer Sep 22 '11 at 08:35
  • The values you are trying to remove are assumed (if the parser is following the rules in the XML specification) to be the default if they aren't specified, so removing them would make no difference! – Quentin Sep 22 '11 at 08:40
  • 1
    UTF-8 is the default encoding of an XML document if there is no Byte-Order-Mark (BOM): http://www.opentag.com/xfaq_enc.htm#enc_default. This means that or are equivalent declaration (without BOM). – Laurent Legrand Sep 22 '11 at 08:44

3 Answers3

15

Why do you need to remove an encoding? But..

doc.setXmlStandalone(true);

will erase standalone="no"

Erik Kaju
  • 3,147
  • 3
  • 19
  • 28
12
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

This would resolve your issue, verified at JDK 6

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Nan chen
  • 137
  • 1
  • 2
  • Dont understand the negative mark on the question. I had the same issue to create a BPEL file and there might be tons other reasons this is needed. So thank you for your answer. Would've taken me ages. – eskalera Jan 22 '13 at 13:30
-1

I think there is no legal way to exclude theese attributes from generation. But after it's generated you can use XSLT to remove this.

I think this is a good way.

Igor Konoplyanko
  • 9,176
  • 6
  • 57
  • 100