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

2

5

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?

Nationalism answered 16/7, 2011 at 1:37 Comment(0)
A
6

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

Airfield answered 16/7, 2011 at 1:43 Comment(3)
é (U+00E9) is supported by ISO-8859-1, so US-ASCII would be better.Crosspollinate
Though I should have started a different thread , but just thinking , with the logic that has been suggested , The Euro Symbol gets replaced by &#128; and it also goes in the xml , But when i try to see it in browser , it just shows nothing . I know the reason for this , that even if the encoding is specified as US-ASCII , the browser treats Numeric character references (such as &#128;) as Unicode characters – no matter what encoding you use for your document. So we send US-ASCII "&#128;" , but that gets interpreted as UTF-8 and so it becomes the control character which is a "blank" ..Jalap
What i wanted to know however is that &8364; works just fine . Is there a JAXB encoding property that allows me to escape characters with these valuesJalap
C
5

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);
  }
}
Crosspollinate answered 16/7, 2011 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.