Search code examples
xmljacksonjackson-dataformat-xml

How to control encoding with Jackson XmlMapper?


I can't find a(n obvious) way to change the encoding for serialized XML from the default UTF-8 to ISO-8859-1. I read the Usage Guide, which makes me think that there must be a way using XMLOutputFactory with XmlFactory to achieve this, but I can't see a way to configure any of those factories to use another encoding by default, there's only createXMLEventWriter where I could pass in an encoding.

I know how to generate the XML declaration using ToXmlGenerator.Feature.WRITE_XML_DECLARATION. So what I need is a declaration like this:

<?xml version='1.0' encoding='ISO-8859-1'?>

And of course the content should be encoded in ISO-8859-1, too.


Solution

  • In the ToXmlGenerator source code, you'll find that UTF-8 is hard coded:

    if (Feature.WRITE_XML_1_1.enabledIn(_formatFeatures)) {
        _xmlWriter.writeStartDocument("UTF-8", "1.1");
    } else if (Feature.WRITE_XML_DECLARATION.enabledIn(_formatFeatures)) {
        _xmlWriter.writeStartDocument("UTF-8", "1.0");
    } else {
        return;
    }
    

    Once ToXmlGenerator is final there might not be an easy way to handle it. I've submitted an issue in the jackson-dataformat-xml project.


    If you stick to JAXB, you can control the value of the encoding attribute using Marshaller.JAXB_ENCODING:

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
    marshaller.marshal(foo, System.out);
    

    See this answer.