我正在尝试解析包含外文字母(特别是 æøå)的 xml,但是我在成功解析它们时遇到了问题。我没有收到任何错误,但这些字母被解析为这样;我得到的不是 æ,而是我得到的不是 å,而是我得到的是 Ã,而不是我得到的 ø 我也刚刚注意到 char - 没有正确显示。 我意识到我可以为 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()
将字符串参数转换为字节。你最好不要转换为字节:
InputSource is = new InputSource(new StringReader(xml));
我看到你在代码中注释掉了。您有什么理由不想使用它吗?
如果您必须使用字节数组,最好这样做:
InputSource is = new InputSource(new ByteArrayInputStream(
xml.getBytes("UTF-8")));
在旧版本的 Android 上,默认字符集取决于语言环境。
关于android - 使用 dom 和特殊字符解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9471129/