3

I have data that I'm serializing that has characters that aren't allowed in xml version 1.0:

<value>this &#18; is not good for 1.0</value>

When RESTEasy serializes this via JAXB it produces this:

<?xml version="1.0" encoding="UTF-8"?>
<value>this &#18; is not good for 1.0</value>

Which XML parsers will not parse as 1.0 does not allow that character, if I set the xml version to 1.1 parsers are happy.

I can do this via:

transformer.setOutputProperty(OutputKeys.VERSION, "1.1");

So what I'm wanting to know is what's the best way to configure jboss / resteasy / jaxb such that when it creates the transformer it uses that it's configured with this output property.

Tom
  • 43,583
  • 4
  • 41
  • 61
  • A JAXB (JSR-222) implementation will typically not create a `Transformer`. Are you looking to influence the XML output by the JAXB impl. – bdoughan May 29 '13 at 17:22
  • @Blaise Good to know, do you know of a good reference for how to lookup this sort of configuration? – Tom May 29 '13 at 17:24

1 Answers1

3

You can set the following on the Marshaller to create a new header.

    // Remove the header that JAXB will generate
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

    // Grab the encoding that will be used for Marshalling
    String encoding = (String) marshaller.getProperty(Marshaller.JAXB_ENCODING);

    // Specify the new header
    marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.1\" encoding=\"" + encoding + "\">");

In a JAX-RS environment you can create a MessageBodyWriter to configure a Marshaller this way. The following answer to a similar question includes an example of how to do this:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • This is good but I'm wanting to configure resteasy such that it does this by default rather than hand code this for every API entry point. – Tom May 29 '13 at 19:15
  • @Tom - I'm not sure you can. However you could create one `MessageBodyWriter` class that would work with many different services. – bdoughan May 29 '13 at 19:24
  • I got this to work in the standalone case but had to change the property set to "com.sun.xml.internal.bind.xmlHeaders" (note the internal). I still haven't figured out how to get this into the marshaller for resteasy. – Tom Jul 03 '13 at 17:26
  • Thanks Tom and Blaise ... the best thing to do seems to be to cover both bases as outlined here: http://timepassguys.blogspot.com/2011/12/jaxb-exception-javaxxmlbindpropertyexce.html ...and this diff from a jersey framework commit also seems to follow this best-practice for sniffing out the right xmlheader key: https://java.net/projects/jersey/lists/commits/archive/2011-03/message/33 – pulkitsinghal Dec 07 '13 at 00:33