How do I add the XML Version and Encoding Declaration to XML?

E

eric.jester

Hello,

I a org.w3c.dom.Document that does not have the <?xml version="1"
encoding="UTF-8"?> declaration on it. Is there a way I can add this to
it?

Thanks,

Eric
 
M

Michael Berg

Hi,
I a org.w3c.dom.Document that does not have the <?xml version="1"
encoding="UTF-8"?> declaration on it. Is there a way I can add this to
it?

What are you using to serialize the Document to XML? In my experience using
the Transformer class from Xerces outputs an XML document that is
appropriately formatted:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// I have to read this stuff manually from time to time so make it pretty
transformer.setOutputProperty(OutputKeys.INDENT,"yes");

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4
");
transformer.transform(new DOMSource(xml),result); // xml is your Document
instance
...
xmlstring = result.toString();

'Result' having been previously created as a StreamResult object - for
example like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(
new java.io_OutputStreamWriter(
baos,
"UTF-8"
)
);

But of course there are many other ways to do this. Your mileage may vary.

/Michael
www.hyperpal.com
www.bergconsult.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top