我目前正在使用以下代码将对象编组为 xml 字符串
JAXBContext context;
try {
context = JAXBContext.newInstance(heartbeat.getClass());
StringWriter writer = new StringWriter();
Marshaller marshaller = context.createMarshaller();
heartbeat.setHeader(header);
heartbeat.setHeartbeatEvent(event);
marshaller.marshal(heartbeat, writer);
String stringXML = writer.toString();
return stringXML;
} catch (JAXBException e) {
throw new RuntimeException("Problems generating XML in specified "
+ "encoding, underlying problem is " + e.getMessage(),
e);
}
产生以下标题
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
我想要的输出如下
<?xml version=\"1.0\"?>
通过将此添加到编组器
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\"?>");
我收到
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><?xml version="1.0"?>
并将 JAXB_FRAGMENT 属性更改为 TRUE 会完全删除标头。我一直在关注JAXB - 从生成的 XML 线程中删除 'standalone="yes"'试图解决问题,但到目前为止我还没有运气。有人可以给我一些关于如何从 JAXB 编组器获取我想要的标头的见解吗?