标签:dom special-characters xml parsing android
我正在尝试解析包含外来字母的xml(特别是æøå),但是在成功解析它们时遇到了问题.我没有任何错误,但是字母被解析为:而不是æ我得到Ã,而不是åim得到Ã¥和øim得到ø
我也只是注意到字符-不能正确显示.
我知道我可以为3个字母做.replaceAll,但是我不确定这里的问题是我在某个地方犯了一个错误,还是如果不沿着replaceAll的路线不可能实现的话.
编码:
private Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new ByteArrayInputStream(
xml.getBytes()));
// is.setCharacterStream(new StringReader(xml));
is.setEncoding("UTF-8");
Log.i(TAG, "Encoding: " + is.getEncoding());
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
private String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
private final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
让我知道您是否需要查看更多代码.
感谢任何建议-谢谢.
解决方法:
问题是您正在使用getBytes()将String参数转换为字节.您最好不要完全转换为字节:
InputSource is = new InputSource(new StringReader(xml));
我看到您在代码中已经注释掉了.您有什么理由不想使用它吗?
如果必须使用字节数组,则最好这样做:
InputSource is = new InputSource(new ByteArrayInputStream(
xml.getBytes("UTF-8")));
在较旧版本的Android上,默认字符集取决于语言环境.
标签:dom,special-characters,xml,parsing,android 来源: https://codeday.me/bug/20191101/1985133.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。