2010-02-08 49 views
2

在我的文本中有芬蘭文字符(例如ä,ö和å),這些字符在XML中是不安全的,有沒有用於此目的的任何庫/框架?如何將不安全的字符轉換爲Java中安全字符的XML?

+4

我不認爲我真的會稱這些字符爲「不安全」。字符編碼必須正確,並匹配XML聲明,就這些了。 – 2010-02-08 09:29:51

+1

顯然,我的servlet響應沒有response.setCharacterEncoding(「UTF-8」);但是當我添加它時,一切正常...... – newbie 2010-02-08 10:03:32

回答

3

XML支持Unicode,因此您唯一需要轉義的就是五個基本的XML實體(gt,lt,quot,amp,apos)。如果您使用StringEscapeUtils.escapeXML,它會將您所有的ä,ö和å變成醜陋的\ uabcd內容。

+0

順便說一句,有一些字符被XML規範視爲非法,無論你如何編碼它們。例如,ASCII NUL字符。 – 2010-02-08 11:49:49

2

所以最好的方法ecsape字符串的XML是StringEscapeUtils.escapeXML Commons Lang,但作爲有人在這裏已經表示,這是不夠的 E.g.有一些不可打印的控制字符,如果想要有效的xml,應該從字符串中刪除。 要做到這一點,我用這個片段:

/** 
* Function to strip control characters from a string. 
* Any character below a space will be stripped from the string. 
* @param iString the input string to be stripped. 
* @return a string containing the characters from iString minus any control characters. 
*/ 
public String stripControlChars(String iString) { 
    StringBuffer result = new StringBuffer(iString); 
    int idx = result.length(); 
    while (idx-- > 0) { 
     if (result.charAt(idx) < 0x20 && result.charAt(idx) != 0x9 && 
       result.charAt(idx) != 0xA && result.charAt(idx) != 0xD) { 
      if (log.isDebugEnabled()) { 
       log.debug("deleted character at: "+idx); 
      } 
      result.deleteCharAt(idx); 
     } 
    } 
    return result.toString(); 
} 

// Then 
String s = org.apache.commons.lang3.StringEscapeUtils.escapeXml(stripControlChars(s)); 

而且使用StringEscapeUtils.escapeXML下議院郎3版作爲方法,其中逃逸更多的則需要對以前的版本中是很重要的。

相關問題