Search code examples
javaxmlversiondomdocumenttransformer-model

Java produce version "1.1" in XML header with transformer


I want to produce xml files with 1.1 as version in the header, since i get SaxparserExceptions when parsing my xml-files with version 1.0:

"Character reference "&#3" is an invalid XML character". 

When I manually change the header, i don't get any errors. Changing the version via outputkeys doesn't seem to work. The file has still the wrong header:

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

example code:

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory
                .newTransformer();

        transformer.setOutputProperty(
                OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.1");
        transformer
                .setOutputProperty(
                        "{http://xml.apache.org/xslt}indent-amount",
                        "2");


        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(
                 "processed_.xml");
        transformer.transform(source, result);

    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Solution

  • Xalan probably doesn't support XML 1.1. Try Saxon instead.