How to stop the Marshaller class adding an XML tag to my output file

I collect my object in 2 separate steps. One adds a Header, and the other adds a Body. Now when i use this code

marshaller.marshal(payload, writer); //payload is Objects name and writer is StringWriter class object 

The XML tag <?xml version="1.0" encoding="utf-8"?> added twice to the final output file.

How can I add the tag [<?xml version="1.0" encoding="utf-8"?>] XML the second time I collect the body part ??

I used all the properties of the Marshaller interface, but this did not help.

+6
source share
2 answers

You need to do the following:

  • Manually write the root element (without using JAXB)
  • Marshal heading object. The root element must be the local root element for the header.
  • Marshal of the body object. The root element must be the local root element for the body.
  • Manually close the root element (without using JAXB)

If possible, use StAX XMLStreamWriter to perform manual recording and sorting. I have a related example on my blog:

Note:

When you marshal into an XML document, you must specify the following property in Marshaller .

 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 
+4
source

Solving this problem was easier than writing your own code.

To avoid this problem, you need to set the JAXB_FRAGMENT property to true in Marshaller. This property lets JAXB know that it is marching in the middle of the document and that it should not write a headline.

So, I stayed below the code before writing the BODY part:

 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 

And it works like a charm!

+3
source

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


All Articles