Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

com.w3c.dom.Document without <?xml version="1.0" encoding="UTF-8" standalone="no"?>

Tags:

java

xml

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.

like image 663
Madi Sagimbekov Avatar asked Feb 07 '13 11:02

Madi Sagimbekov


People also ask

What does Standalone no mean in XML?

The XML standalone element defines the existence of an externally-defined DTD. In the message tree it is represented by a syntax element with field type XML. standalone. The value of the XML standalone element is the value of the standalone attribute in the XML declaration.


1 Answers

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.
like image 87
Xavi López Avatar answered Sep 23 '22 12:09

Xavi López