Java在带有转换器的XML头中生成版本“1.1”

时间:2014-09-08 16:30:01

标签: java xml version domdocument transformer

我想在头文件中生成1.1版本的xml文件,因为在使用版本1.0解析我的xml文件时我得到了SaxparserExceptions:

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

当我手动更改标题时,我不会收到任何错误。通过outputkeys更改版本似乎不起作用。该文件仍有错误的标题:

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

示例代码:

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

2 个答案:

答案 0 :(得分:1)

Xalan可能不支持XML 1.1。试试撒克逊。

答案 1 :(得分:0)

doc.setXmlVersion(“ 1.1”);为我工作。