您可以配置编写 XML 标头。XmlMapper
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
例如:
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import java.io.IOException;
public class Xml {
public static void main(String[] args) throws IOException {
// Important: create XmlMapper; it will use proper factories, workarounds
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.writeValue(System.out, new SampleRequest());
}
}
class SampleRequest{
public int x = 1;
public int y = 2;
}
这将生成输出:
<?xml version="1.0" encoding="UTF-8"?>
<SampleRequest>
...
</SampleRequest>
如果要将版本设置为 1.1 而不是 1.0,请使用 .ToXmlGenerator.Feature.WRITE_XML_1_1
请注意,Faster-XML 团队建议使用 Woodstox 库。如果您使用它,可以设置一些其他配置。在所有这些中,有一个与设置双引号有关:
public static final String P_USE_DOUBLE_QUOTES_IN_XML_DECL="com.ctc.wstx.useDoubleQuotesInXmlDecl";
在WstxOutputProperties.java
有关更多详细信息,请查看配置Woodstox解析器。