我试图获取带有一些 Unicode 字符的 XML 输出。我无法读取标签内的完整字符串,只能读取一个。
这是我的 XML 输出
<item>
<id>1</id>
<name>ලොල්</name>
<cost>155</cost>
<description>ලො</description>
</item>
这是我用来解析 XML 字符串的 java 代码。
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setEncoding("UTF-16");
is.setCharacterStream(new StringReader(xml));
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;
}
当我使用普通英文字符时,它会给出完整的字符串。
最佳答案
我已经尝试过你的代码,没有问题。如果我用非英语字符评估节点,则节点存在并且具有正确的字符数。它们不可打印,因为我使用的字体中没有该字形,但 value.codePointAt(i)
返回正确的代码点。
NodeList list = doc.getDocumentElement().getChildNodes();
for (int i=0; i<list.getLength(); i++)
{
String value = list.item(i).getTextContent();
for (int j=0; j<value.length(); j++)
System.out.print(" " + value.codePointAt(j));
System.out.println();
}
输出:
49
3517 3548 3517 3530
49 53 53
3517 3548
对应于代码点的十进制表示形式。
我已经手动创建了 xml 字符串。你已经记住了,对吗?
关于java - 在 Java/Android 中读取 XML 中的 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526061/