【发布时间】: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