Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent JAXB escaping a string

Tags:

java

jaxb

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?

like image 510
rjsang Avatar asked Jul 20 '10 10:07

rjsang


People also ask

Is JAXB context thread safe?

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.

What is marshalling and unmarshalling in JAXB?

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.

What is marshalling in JAXB?

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.

Is JAXB fast?

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.


2 Answers

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 image 151
Manish Singh Avatar answered Sep 27 '22 01:09

Manish Singh


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");
like image 23
jfuentes Avatar answered Sep 25 '22 01:09

jfuentes