【问题标题】:Write unicode 0x2 in Java用Java编写unicode 0x2
【发布时间】:2013-03-02 01:16:11
【问题描述】:

如何在 Java 中编写 unicode 字符 0x{2}

我尝试使用"\u0002",但似乎不起作用。

我需要找到这个字符的原因是因为我需要在 XML 文件中替换它,然后才能解析它。

我在解析提及时遇到的错误:An invalid XML character (Unicode: 0x{2}) was found in the value of attribute "{1}" and element is "4". 并替换 \u0002 并不能解决该错误。

这就是我的解析方式:

try {
    // Fixing any invalid characters in the XML file
    fixXMLFile(xmlFile);

    // Get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();

    // Get a new instance of parser
    SAXParser sp = spf.newSAXParser();

    // Parse the file and also register this class for call backs
    sp.parse(xmlFile, this);

} catch(Exception e) {
    System.out.println(e.getLocalizedMessage());
}

以及修复方法:

private void fixXMLFile(File xmlFile) throws IOException {
    File tempFile = File.createTempFile("dont_delete", ".tmp");
    FileWriter fw = new FileWriter(tempFile);

    Reader fr = new FileReader(xmlFile);
    BufferedReader br = new BufferedReader(fr);

    int sdds = 0;
    while(br.ready()) {
        String tmp = br.readLine();
        if (tmp.contains("\u0002")) System.out.println(++sdds);
        fw.write(tmp.replaceAll("\u0002", "") + "\n");
    }

    fw.close();
    br.close();
    fr.close();

    // Finally replace the original file.
    tempFile.renameTo(xmlFile);
}

【问题讨论】:

  • 您使用\u0002时有什么问题?
  • 简单:if (myString.contains("\u0002")) System.out.println("Found it"); 这个没找到。
  • 你们可以停止投票并阅读实际问题吗?
  • 那么你怎么知道它在那里?用文本板等其他工具搜索?您是否将字符与转义值混淆了?
  • 您可以发布一些源代码和/或您要解析的文件吗?

标签: java unicode character-encoding


【解决方案1】:

我找到了。错误消息中的 0x{2} 在 Java 中是 "\u0004"。替换即可消除错误消息。

【讨论】:

  • 我的猜测是您的 SAX 库有一个错误,应该将 {2} 扩展为 0004,将 {1} 扩展为包含 \u0004 的任何属性。
  • 我同意艾蒂安的观点。解析器作者似乎打算将该错误消息用作MessageFormat 格式字符串,但忘了这样做。 {1}{2} 是格式参数的占位符。
【解决方案2】:

不允许的字符是 XML,请参阅维基百科的参考:http://en.wikipedia.org/wiki/Valid_characters_in_XML#XML_1.0

【讨论】:

  • 我知道这是不允许的。这就是为什么我在上面的问题中询问如何替换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2012-01-04
  • 2011-02-01
  • 2013-05-13
  • 2016-05-01
  • 2016-12-04
相关资源
最近更新 更多