rjsang
rjsang

Reputation: 1757

How to prevent JAXB escaping a string

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?

Upvotes: 15

Views: 36692

Answers (6)

ZiglioUK
ZiglioUK

Reputation: 2610

Solution for XmlStreamWriter

final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory();
streamWriterFactory.setProperty("escapeCharacters", false);

From here

Upvotes: 2

Carlitos Way
Carlitos Way

Reputation: 3424

If you implement this interface: com.sun.xml.bind.marshaller.CharacterEscapeHandler, with your own character escaping, but you want to delegate some behaviour to the traditional escaping, you can use any of these clases (or write your own code based on them):

  • com.sun.xml.bind.marshaller.MinimumEscapeHandler
  • com.sun.xml.bind.marshaller.NioEscapeHandler
  • com.sun.xml.bind.marshaller.DumbEscapeHandler

They come with the JAXB RI Implementation AKA jaxb-impl-2.2.1.jar.

Hope this help to anyone, like it helped me.

Upvotes: 1

fred
fred

Reputation: 75

Depending on what you are exactly looking for you can either :

  • disable character escaping
  • or use CDATA string which support can be added into JAXB with just a bit of configuration

Upvotes: -2

jfuentes
jfuentes

Reputation: 71

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

Upvotes: 7

bdoughan
bdoughan

Reputation: 148977

How about using a CDATA section to wrap the value, and then use a JAXB implementation such as EclipseLink MOXy that can handle CDATA?

To handle CDATA using MOXy see:

Upvotes: 0

Manish Singh
Manish Singh

Reputation: 3499

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

Upvotes: 15

Related Questions