gpt4 book ai didi

Java jaxb utf-8/iso 转换

转载 作者:行者123 更新时间:2023-12-01 04:27:34 26 4
gpt4 key购买 nike

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

我使用 UTF-8/ISO/ascii + 解码读取 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 代码,并将它们转换/映射为“文字”符号。即:“’”=>“左单引号”

使用 iso 进行 JAXB 解码,可以很好地显示经过 iso 转换的字符。即所有奇怪的单引号都将被编码为“’”

所以假设我的字符串是:class of 10–11‐year-olds(注意奇怪的 - 11 到year之间)

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解码输出:

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 编码字符吗?

最佳答案

已解决:使用在 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)

关于Java jaxb utf-8/iso 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com