Java tutorial
//package com.java2s; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class Main { private static XMLInputFactory xif = XMLInputFactory.newInstance(); private static final byte[] XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" .getBytes(Charset.forName("UTF-8")); public static byte[] prependXmlDeclaration(byte[] doc) throws Exception { if (!hasValidXmlDeclaration(doc)) { byte[] newdoc = new byte[doc.length + XML_DECL.length]; System.arraycopy(XML_DECL, 0, newdoc, 0, XML_DECL.length); System.arraycopy(doc, 0, newdoc, XML_DECL.length, doc.length); return newdoc; } else { return doc; } } public static boolean hasValidXmlDeclaration(byte[] doc) throws Exception { try { XMLStreamReader r = xif.createXMLStreamReader(new ByteArrayInputStream(doc), null); if (!"UTF-8".equalsIgnoreCase(r.getEncoding())) return false; if (!"1.0".equals(r.getVersion())) return false; r.close(); return true; } catch (XMLStreamException e) { throw new Exception("Unable to parse xml", e); } } }