1. 程式人生 > >字串序列化時碰到的小問題

字串序列化時碰到的小問題

最近在使用.NET當中的序列化方法序列化字串時碰到一個小問題。序列化時一切正常,反序列化時卻

碰到了問題。
先看程式碼:

輸出結果:
TestClass1.TestMethod1 passed!
TestClass1.TestMethod2 failed!

Debug發現TestMethod1的序列化結果是:

TestMethod2的序列化結果是:

如果我們把TestMethod2的這段Xml存為一個檔案,然後用Visual Studio開啟,會發現有以下的錯誤提示:

Error 3 Character ' ', hexadecimal value 0x1 is illegal in XML documents. XMLFile2.xml 3 14 Miscellaneous Files
Error 4 Character ' ', hexadecimal value 0x2 is illegal in XML documents. XMLFile2.xml 3 19 Miscellaneous Files
Error 5 Character ' ', hexadecimal value 0x3 is illegal in XML documents. XMLFile2.xml 3 24 Miscellaneous Files
Error 6 Character ' ', hexadecimal value 0x4 is illegal in XML documents. XMLFile2.xml 3 29 Miscellaneous Files

這下我們明白了,原來就是:...這些個特殊字元在作怪。網上搜了一把,這個過程比較鬱悶,不知道該用什麼關鍵字去搜,後來直接在Google裡試了一下“&#x1”發現前兩個就是和我相似的問題,其中第一個裡面講到了MSDN裡面的原文

參考這裡吧:

特別是MSDN的原文:

這下就明白了,我反序列化的時候沒有直接用到XmlTextReader,而Normalization預設是true,而是用的StringReader把字串讀取為流,只要把反序列化的方法稍微改改就行:

 

好了,完事大吉!

最後奉上測試程式碼:測試程式碼