您好我正在使用faster-xml(https://github.com/FasterXML/jackson-dataformat-xml/wiki)将java POJO对象序列化为xml。当我这样做时,我得到了xml,但它在xml文件中没有任何版本和编码。这是格式我需要
<?xml version="1.0" encoding="utf-8"?>
<SampleRequest>
...
</SampleRequest>
但我只得到了这一个
<SampleRequest>
...
</SampleRequest>
是否需要在jackson fasterxml anotation中添加任何配置。
答案 0 :(得分:23)
您可以配置 XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
以编写XML标头。
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>
这会生成输出:
ToXmlGenerator.Feature.WRITE_XML_1_1
如果您想将版本设置为 1.1 而不是 1.0 ,请使用{{1}}。
答案 1 :(得分:2)
<div class="square"> <img class="square__img" src="square.png"> </div>
<div class="square square--small"> <img class="square__image" src="square.png"> </div>
答案 2 :(得分:1)
对于那些想知道如何将单引号更改为双引号的人:
String propName = com.ctc.wstx.api.WstxOutputProperties.P_USE_DOUBLE_QUOTES_IN_XML_DECL;
xmlMapper.getFactory()
.getXMLOutputFactory()
.setProperty(propName, true);