How to prevent JAXB escaping a string

2019-01-14 13:22发布

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?

标签: java jaxb
6条回答
够拽才男人
2楼-- · 2019-01-14 13:43

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
查看更多
3楼-- · 2019-01-14 13:44

Solution for XmlStreamWriter

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

From here

查看更多
放荡不羁爱自由
4楼-- · 2019-01-14 13:50

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.

查看更多
来,给爷笑一个
5楼-- · 2019-01-14 14:00

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

查看更多
做个烂人
6楼-- · 2019-01-14 14:02

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:

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-14 14:03

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");
查看更多
登录 后发表回答