我目前正在使用以下代码将对象编组为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 - Remove 'standalone="yes"' from generated XML线程,但到目前为止我没有运气。有人可以给我一些关于如何从JAXB marshaller获取所需标题的见解吗?
答案 0 :(得分:18)
使用以下组合编组到OutputStream
时会产生预期的输出。
marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\"?>");
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
当您编组到Writer
时,您看到的问题就出现了,这似乎是JAXB参考实现中的错误。您可以通过以下链接提出问题:
你总是可以这样做:
JAXBContext context;
try {
context = JAXBContext.newInstance(heartbeat.getClass());
StringWriter writer = new StringWriter();
writer.append("<?xml version=\"1.0\"?>");
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
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);
}
EclipseLink JAXB (MOXy)也支持com.sun.xml.bind.xmlHeaders
,当它编组为Writer
时,它可以正常工作(我是MOXy领导)
答案 1 :(得分:7)
这对我有用
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");