Posted on 2008-09-04 15:18
Fingki.li 閱讀(12202)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
About development
About Exception:
An invalid XML character (Unicode: 0x0) was found in the element content of the document.
問(wèn)題描述:
當(dāng)我們用
byte[] info ;
DocumentHelper.parseText(new String(info));
將一個(gè)字節(jié)數(shù)組轉(zhuǎn)成字符串再轉(zhuǎn)成Document(XML格式)時(shí),常常會(huì)遇到上述異常。
特別是當(dāng)字符串有加、解密,或編碼等情況時(shí)。
原因:
從異常來(lái)看,很明顯是因?yàn)樽止?jié)數(shù)組中存在 Unicode: 0x0,而這個(gè)字節(jié)在Xml中被認(rèn)為是非法字符。
對(duì)于一些經(jīng)過(guò)編碼或加、解密的字符串中,很容易會(huì)出現(xiàn)這個(gè) 0x0,
特別是在加、解密中,經(jīng)常會(huì)涉及到字符填充,而填充物通常是 0x0,
需對(duì)于0x00-0x20 都會(huì)引起一定的問(wèn)題,又因?yàn)檫@些字符不可見(jiàn),因此用通常的編輯器進(jìn)行編輯的時(shí)候找不到問(wèn)題所在。
而在轉(zhuǎn)成String后也覺(jué)察不到任何異常。
所以在轉(zhuǎn)成XML格式時(shí)要對(duì)字符串進(jìn)行檢測(cè):
* Verify that no character has a hex value greater than 0xFFFD, or less than 0x20.
* Check that the character is not equal to the tab ("t), the newline ("n), the carriage return ("r), or is an invalid XML character below the range of 0x20. If any of these characters occur, an exception is thrown.
pubic void CheckUnicodeString(String value)
{
for (int i=0; i < value.Length; ++i) {
if (value[i] > 0xFFFD)
{
throw new Exception("Invalid Unicode");//或者直接替換掉0x0 value[i]='"n';
}
else if (value[i] < 0x20 && value[i] != '"t' & value[i] != '"n' & value[i] != '"r')
{
throw new Exception("Invalid Xml Characters");//或者直接替換掉0x0 value[i]='"n';
}
}
相關(guān)資源:
http://msdn.microsoft.com/en-us/library/k1y7hyy9.aspx
http://gceclub.sun.com.cn/developer/technicalArticles/Intl/Supplementary/index_zh_CN.html