Changing the XML Header Created by the JAXB Marshaller

I am currently using the following code to marshal an object into an xml string

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); } 

What creates the following heading

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 

My desired result is as follows

 <?xml version=\"1.0\"?> 

Adding this to the Marshaller

 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE); marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\"?>"); 

I get

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><?xml version="1.0"?> 

and changing the JAXB_FRAGMENT property to TRUE completely removes the header. I am following JAXB - Remove 'standalone = "yes"' from the generated XML stream trying to solve the problem, but still no luck. Can someone please give me some idea on how to get the desired header from a JAXB marshaller?

+6
source share
2 answers

When sorting using an OutputStream using a combination of the following results, the expected result is expected.

  marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\"?>"); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 

The problem you see occurs when you marshal on Writer , which appears to be a bug in the JAXB reference implementation. You can ask a question at the link below:


You can always do:

 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) also supports com.sun.xml.bind.xmlHeaders , and it works correctly when sorting on Writer (I am the leader of MOXy)

+13
source

It worked for me

marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

+7
source

Source: https://habr.com/ru/post/952531/


All Articles