Java jaxb utf-8 / iso转换

时间:2013-08-22 14:11:58

标签: java utf-8 jaxb iso-8859-1

我有一个包含非标准字符的XML文件(比如奇怪的“引用”)。

我使用UTF-8 / ISO / ascii + unmarshalled读取XML:

BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream()),"ISO-8859-1"));
        String output;
        StringBuffer sb = new StringBuffer();
        while ((output = br.readLine()) != null) {
            //fetch XML
            sb.append(output);
        }


        try {

            jc = JAXBContext.newInstance(ServiceResponse.class);

            Unmarshaller unmarshaller = jc.createUnmarshaller();

            ServiceResponse OWrsp =  (ServiceResponse) unmarshaller
                    .unmarshal(new InputSource(new StringReader(sb.toString())));

我有一个oracle函数,它将采用iso-8859-1代码,并将它们转换/映射为“literal”符号。即:“&#x2019”=> “左单引号”

使用iso的JAXB unmarshal,显示iso转换精细的字符。即所有奇怪的单引号都将被编码为“&#x2019”

所以假设我的字符串是:10-11岁的班级(注意奇怪 - 介于11和年之间)

jc = JAXBContext.newInstance(ScienceProductBuilderInfoType.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
        //save a temp file
        File file2 = new File("tmp.xml");

这将保存在文件中:

class of 10–11‐year‐olds. (what i want..so file saving works!)

[旁注:我已经使用java文件阅读器读取了文件,并且输出上面的字符串很好]

我遇到的问题是使用jaxb unmarshaller的STRING表示具有奇怪的输出,由于某种原因我似乎无法获得表示的字符串 - 。

当我 1:检查xml unmarshalled输出:

class of 10?11?year?olds

2:文件输出:

class of 10–11‐year‐olds

我甚至尝试从保存的XML中读取文件,然后解组(希望在我的字符串中获取 - )

String sCurrentLine;
        BufferedReader br = new BufferedReader(new FileReader("tmp.xml"));
        StringBuffer sb = new StringBuffer();
        while ((sCurrentLine = br.readLine()) != null) {
            sb.append(sCurrentLine);
        }




        ScienceProductBuilderInfoType rsp =  (ScienceProductBuilderInfoType) unm
                .unmarshal(new InputSource(new StringReader(sb.toString())));

无济于事。

如何在jaxb中获取iso-8859-1编码字符?

1 个答案:

答案 0 :(得分:0)

解决:使用stackoverflow上找到的这个tibid代码

final class HtmlEncoder {
  private HtmlEncoder() {}

  public static <T extends Appendable> T escapeNonLatin(CharSequence sequence,
      T out) throws java.io.IOException {
    for (int i = 0; i < sequence.length(); i++) {
      char ch = sequence.charAt(i);
      if (Character.UnicodeBlock.of(ch) == Character.UnicodeBlock.BASIC_LATIN) {
        out.append(ch);
      } else {
        int codepoint = Character.codePointAt(sequence, i);
        // handle supplementary range chars
        i += Character.charCount(codepoint) - 1;
        // emit entity
        out.append("&#x");
        out.append(Integer.toHexString(codepoint));
        out.append(";");
      }
    }
    return out;
  }
}

HtmlEncoder.escapeNonLatin(MyString的)