I’m using Java 6. I have an XML template, which begins like so
<?xml version="1.0" encoding="UTF-8"?>
However, I notice when I parse and output it with the following code (using Apache Commons-io 2.4) …
Document doc = null;
InputStream in = this.getClass().getClassLoader().getResourceAsStream(“my-template.xml”);
try
{
byte[] data = org.apache.commons.io.IOUtils.toByteArray( in );
InputSource src = new InputSource(new StringReader(new String(data)));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(src);
}
finally
{
in.close();
}
The first line is output as
<?xml version="1.0" encoding="UTF-16”?>
What do I need to do when parsing/outputting the file so that the header encoding will remain “UTF-8”?
Edit: Per the suggestion given, I changed my code to
Document doc = null;
InputStream in = this.getClass().getClassLoader().getResourceAsStream(name);
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(in);
}
finally
{
in.close();
}
But despite the fact my input element template file's first line is
<?xml version="1.0" encoding="UTF-8"?>
when i output the document as a String it produces
<?xml version="1.0" encoding="UTF-16"?>
as a first line. Here's what I use to output the "doc" object as a string ...
private String getDocumentString(Document doc)
{
DOMImplementationLS domImplementation = (DOMImplementationLS)doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
return lsSerializer.writeToString(doc);
}