Marcin Wasiluk
Marcin Wasiluk

Reputation: 4884

dom4j XML declaration in document

I need to remove XML declaration from dom4j document type

I am creating document by

doc = (Document) DocumentHelper.parseText(someXMLstringWithoutXMLDeclaration);

String parsed to Document doc by DocumenHelper contains no XML declaration (it comes from XML => XSL => XML transformation) I think that DocumentHelper is adding declaration to a document body ?

Is there any way to remove XML declaration from the body of

doc

Upvotes: 3

Views: 3742

Answers (3)

Jerry Meng
Jerry Meng

Reputation: 81

The simpler solution I choose is

doc.getRootElement().asXML();

Upvotes: 8

Kirby
Kirby

Reputation: 15875

You need to interact with the root element instead of the document. For example, using the default, compact OutputFormat mentioned by PhilW:

Document doc = (Document) DocumentHelper.parseText(someXMLstringWithoutXMLDeclaration);    
final Writer writer = new StringWriter();
new XMLWriter(writer).write(doc.getRootElement());
String out = writer.toString();

Upvotes: 2

PhilW
PhilW

Reputation: 751

I'm not sure where exactly this the declaration is a problem in your code. I had this once when I wanted to write an xml file without declaration (using dom4j).

So if this is your use case: "omit declaration" is what you're looking for. http://dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/io/OutputFormat.html

Google says this can be set as a property as well, not sure what it does though.

Upvotes: 2

Related Questions