2013-03-13 76 views
3

如何在Java中編寫Unicode字符0x{2}在Java中寫入unicode 0x2

我試用"\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); 
} 
+0

當你使用'\ u0002'時什麼都不起作用? – 2013-03-13 21:14:15

+0

簡單:'if(myString.contains(「\ u0002」))System.out.println(「找到它」);'這找不到它。 – Dimme 2013-03-13 21:18:01

+0

您可以停止投票並閱讀實際問題嗎? – Dimme 2013-03-13 21:24:51

回答

0

我發現它。錯誤消息中的0x{2}是Java中的"\u0004"。替換消除了錯誤消息。

+1

我的猜測是你的SAX庫有一個bug,並且應該將0004和{1}用於任何屬於\ u0004的屬性。 – 2013-03-13 22:03:36

+1

我同意艾蒂安。看起來,解析器作者打算將該錯誤消息用作'MessageFormat'格式字符串,但忘記了這樣做。 「{1}」和「{2}」是格式參數的佔位符。 – VGR 2013-03-13 23:49:04