I have an object, generated by XJC, called Product
. I want to set product.currentPrice (a String)
to be £210
where £
is the currency symbol (passed in from elsewhere in the system).
Trouble is, JAXB is escaping my ampersand, so it produces £210
instead. How do I make it not do this?
JAXBContext is thread safe and should only be created once and reused to avoid the cost of initializing the metadata multiple times. Marshaller and Unmarshaller are not thread safe, but are lightweight to create and could be created per operation.
JAXB definitionsMarshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects. The JAXBContext class provides the client's entry point to the JAXB API. It provides API for marshalling, unmarshalling and validating.
The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling to XML can be done to variety of output targets.
Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications.
By default, the marshaller implementation of the JAXB usually escapes characters. To change this default behavior you will have to Write a class that implements the com.sun.xml.bind.marshaller.CharacterEscapeHandler
interface.
set that handler in the Marshaller
CharacterEscapeHandler escapeHandler = NoEscapeHandler.theInstance;
marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", escapeHandler);
You can have a look at samples provided with JAXB, character escaping sample
Like rjsang said, there is a bug when using "UTF-8" encoding, which is the default. If you don't care about the case sensitive issues, try using "utf-8" and get your custom escaper to work as it is supposed to do. Also UTF-16 works, anything but "UTF-8": "uTf-8" and so on.
Awful bug in the standard.
Here is the code to do so:
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "utf-8");
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