java javax.xml.bind.Marshaller 用十进制值编码 unicode 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6714704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:59:10  来源:igfitidea点击:

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

javaxmlutf-8axis2

提问by partkyle

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

我有一个需要生成 xml 的服务。目前我正在使用 jaxb 和 Marshaller 使用 StringWriter 创建 xml。

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:

虽然这对于某些网络服务可能没问题,但我需要转义特殊的 unicode 字符。使用我的 xml 的服务需要有这个:

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

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

如果我使用StringEscapeUtilsfromcommons-lang我最终会得到类似以下内容的东西。这个也不起作用:

<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?

Marshaller 是否有一些设置允许我将这些特殊字符编码为它们的十进制值?

回答by Ed Staub

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

是的, Marshaller.setProperty(jaxb.encoding, encoding) 将设置用于文档的编码。我猜你想要“US-ASCII”。

回答by McDowell

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

正如Ed Staub 建议的那样,尝试设置jaxb.encoding属性。该US-ASCII编码将导致任何的前128个码点以上进行转义。

@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);
  }
}