7
votes

I am creating a com.w3c.dom.Document from a String using this code:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader("<a><b id="5"/></a>")));

When I System.out.println(xmlToString(document)), I get this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b id="5"/></a>

Everything is ok, but I don't want the XML to have the <?xml version="1.0" encoding="UTF-8" standalone="no"?> declaration, because I have to sign the with private key and embed to soap envelope.

1

1 Answers

12
votes

You could use a Transformer and set the OutputKeys.OMIT_XML_DECLARATION property to "yes":

Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(doc), new StreamResult(sw));

Please note you could also:

  • Use a StreamSource instead of a DOMSource to feed the String directly to the transformer, if you don't really need the Document.
  • Use a DOMResult instead of a StreamResult if you wanted to output a Document.