首页 > 解决方案 > 如何使用 Java 中的 jaxb 和 XMLStreamWriter 在 Prolog 中将单引号更改为双引号以最终 XML

问题描述

我有一个完美的解决方案来将对象编组为最终的 XML:

final String XSD_FILE_NAME = "my.xsd"

public void writeToFile(MyFile myFile) {
    try (OutputStream writer = new FileOutputStream(exactFilePath)) {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setSchema(resourceLoader.getResource("classpath:file/my.xsd"));
        marshaller.setContextPath("com.my.project.type");
        marshaller.setMarshallerProperties(ImmutableMap.of(
                javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE,
                javax.xml.bind.Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "my.xsd"
        ));
        marshaller.afterPropertiesSet();

        XMLStreamWriter streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer, "UTF-8");
        StAXResult result = new StAXResult(streamWriter);
        marshaller.marshal(myFile, result);
        streamWriter.close();
    } catch (IOException | XMLStreamException e) {
        throw e;
    }
}

但我意识到最终的 XML 文件只对 Prolog ( <?xml ...>) 使用单引号。但是对于根元素和子元素中的所有其他属性,双引号:

<?xml version='1.0' encoding='UTF-8'?>
<myFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attribute1="1" attribute2="2">
  <myChild/>
</myFile>

如何将它设置为对 XML Prolog 也使用双引号?

标签: xmlspringjaxbmarshalling

解决方案


如果你的工厂是伍德斯托克。

XMLOutputFactory xif = XMLOutputFactory.newFactory();
 xif.setProperty("com.ctc.wstx.useDoubleQuotesInXmlDecl","true");

推荐阅读