Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.xml.bind.Marshaller encoding unicode characters with their decimal values

I have a service that needs to generate xml. Currently I am using jaxb and a Marshaller to create the xml using a StringWriter.

Here is the current output that I am getting.

<CompanyName>Bakery é &amp;</CompanyName>

While this may be fine for some webservices, I need to escape special unicode characters. The service that is comsuming my xml needs to have this:

<CompanyName>Bakery &#233; &amp;</CompanyName>

If I use StringEscapeUtils from commons-lang I end up with something like the follwing. This one does not work also:

<CompanyName>Bakery &amp;#233; &amp;amp;</CompanyName>

Are there some settings for the Marshaller that will allow me to encode these special characters as their decimal values?

like image 455
partkyle Avatar asked Dec 22 '22 11:12

partkyle


2 Answers

Yes, Marshaller.setProperty(jaxb.encoding,encoding) will set the encoding to use for the document. I'd guess that you want "US-ASCII".

like image 87
Ed Staub Avatar answered Dec 24 '22 01:12

Ed Staub


As Ed Staub suggests, try setting the jaxb.encoding property. The US-ASCII encoding will cause anything above the first 128 code points to be escaped.

@XmlRootElement(name = "Company")
public class Company {
  private String companyName = "Bakery \u00E9 &";

  @XmlElement(name = "CompanyName")
  public String getCompanyName() { return companyName; }
  public void setCompanyName(String bar) { this.companyName = bar; }

  public static void main(String[] args) throws Exception {
    JAXBContext ctxt = JAXBContext.newInstance(Company.class);
    Marshaller m = ctxt.createMarshaller();
    m.setProperty("jaxb.encoding", "US-ASCII");
    m.marshal(new Company(), System.out);
  }
}
like image 24
McDowell Avatar answered Dec 24 '22 01:12

McDowell