更改JAXB marshaller生成的XML标头

我目前正在使用以下代码将对象编组为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); } 

这会产生以下标题

  

我想要的输出如下

  

通过将此添加到marshaller

 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE); marshaller.setProperty("com.sun.xml.bind.xmlHeaders", ""); 

我收到

  

并将JAXB_FRAGMENT属性更改为TRUE将完全删除标头。 我一直关注JAXB – 从生成的XML线程中删除’standalone =“yes”’试图解决问题,但到目前为止我没有运气。 有人可以给我一些关于如何从JAXB marshaller获取所需标题的见解吗?

使用以下组合编组到OutputStream会产生预期的输出。

  marshaller.setProperty("com.sun.xml.bind.xmlHeaders", ""); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 

当您编组到Writer时,您看到的问题就出现了,这似乎是JAXB参考实现中的错误。 您可以通过以下链接提出问题:


你可以随时做:

 JAXBContext context; try { context = JAXBContext.newInstance(heartbeat.getClass()); StringWriter writer = new StringWriter(); writer.append(""); 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主管)

这对我有用

marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "");