【问题标题】:Read unicode characters in XML in Java/Android在 Java/Android 中读取 XML 中的 unicode 字符
【发布时间】:2012-09-21 07:31:51
【问题描述】:

我试图获取带有一些 Unicode 字符的 XML 输出。我无法读取标签内的完整字符串,只能读取一个。

这是我的 XML 输出

 <item>
    <id>1</id>    
    <name>&#x0DBD;&#x0DDC;&#x0DBD;&#x0DCA;</name>
    <cost>155</cost>
    <description>&#x0DBD;&#x0DDC;</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;
}

当我使用普通英文字符时,它会给出完整的字符串。

【问题讨论】:

  • 当您尝试解析非英语字符时会发生什么?字符串不正确?还是失败了?
  • 它不会失败。它只读取第一个字符。在这个例子中它只输出 ල不是 ලොල්
  • 哦,好的。但接下来有两件事:valueOfTheContainedText.length() 返回 1 还是 4?以及 xml,如果你在解析之前打印它,是吗?

标签: java android xml-parsing xml-serialization


【解决方案1】:

我试过你的代码,没有问题。如果我使用非英语字符评估节点,则存在并且具有正确数量的字符。它们不可打印,因为我没有使用字体中的字形,但 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 字符串。你已经在记忆中了吧?

【讨论】:

  • 这对我有很大帮助。但使用这种方法我无法逐个节点读取。我会把我的代码放在这里。非常感谢。
【解决方案2】:
  • 人们通常使用 Unicode 表示 UTF-8,但您使用的是 UTF-16,即 bad

  • XML 在其header 中定义了自己的编码,因此您不需要覆盖它

【讨论】:

  • 我在想它,但实际上他试图从内存中的字符串读取,所以实际上将字符编码设置为 InputSource 没有效果。它已经感觉到它在内存字符串中的 xml 没有任何编码头,因为它已经被解码了。
【解决方案3】:

这是我用来解决问题的代码。

   NodeList idlist = doc.getElementsByTagName(KEY_ID);
    NodeList namelist = doc.getElementsByTagName(KEY_NAME);
    NodeList costlist = doc.getElementsByTagName(KEY_COST);
    NodeList desclist = doc.getElementsByTagName(KEY_DESC);
    for (int i=0; i<idlist.getLength(); i++)
    {
        Item item = new Item();
        item.setCost(costlist.item(i).getTextContent());
        item.setDescription(desclist.item(i).getTextContent());
        item.setName(namelist.item(i).getTextContent());
        itemarray.add(item);

    }

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2011-04-24
    • 2015-04-05
    • 2021-05-13
    相关资源
    最近更新 更多