Apache Commons IO如何将我的XML标头从UTF-8转换为UTF-16?

问题描述:

我正在使用Java6.我有一个XML模板,它的开头是这样

I’m using Java 6. I have an XML template, which begins like so

<?xml version="1.0" encoding="UTF-8"?>

但是,我注意到当我解析并输出以下代码时(使用Apache Commons-io 2.4)……

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();
    }

第一行输出为

<?xml version="1.0" encoding="UTF-16"?>

解析/输出文件时我需要做什么,以便标头编码保持"UTF-8"?

What do I need to do when parsing/outputting the file so that the header encoding will remain "UTF-8"?

根据给出的建议,我将代码更改为

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"?>

作为第一行.这就是我将"doc"对象输出为字符串的方式...

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);  
}

结果是,当我将Document-> String方法更改为

Turns out that when I changed my Document -> String method to

private String getDocumentString(Document doc)
{
    String ret = null;
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try
    {
        transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        ret = writer.toString();
    }
    catch (TransformerConfigurationException e)
    {
        e.printStackTrace();
    }
    catch (TransformerException e)
    {
        e.printStackTrace();
    }
    return ret;
}

'encoding ="UTF-8"'标头不再输出为'encoding ="UTF-16"'.

the 'encoding="UTF-8"' headers no longer got output as 'encoding="UTF-16"'.