I am marshalling my Object in 2 separate steps. One adds Header and the other one adds the 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"?>
is added twice in the final output file.
How can I not add the [<?xml version="1.0" encoding="utf-8"?>]
XML tag second time when I am marshalling the body part??
I have used all the properties of Marshaller interface, but that did not help.
Object/XML Mapping, or O/X mapping for short, is the act of converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization.
JAXB provides a fast and convenient way to marshal (write) Java objects into XML and unmarshal (read) XML into objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.
The -jaxb. fragment command determines whether the marshaller generates document-level events in the XML data. This command is optional. If you omit it, the default is false. Document-level events are not generated in the XML data.
"The Marshaller provides two styles of callback mechanisms that allow application specific processing during key points in the unmarshalling process. In 'class defined' event callbacks, application specific code placed in JAXB mapped classes is triggered during marshalling.
The solution to this problem was quite simpler than writing my own code.
You need to specify JAXB_FRAGMENT property to true on the Marshaller to avoid this problem. This property lets JAXB know it's marshalling into the middle of a document and that it shouldn't write the header.
So I kept below code, just before writing the BODY part :
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
And it works like a charm!
You need to do the following:
If possible use a StAX XMLStreamWriter
to do the manual writing and the marshalling. I have a related example on my blog:
Note:
When you marshal into an XML document you must specify the following property on the Marshaller
.
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With