字符串序列化时碰到的小问题

来源:互联网 发布:c语言查找字符串位置 编辑:程序博客网 时间:2024/06/03 18:16

最近在使用.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里面的原文

参考这里吧:

http://bytes.com/groups/net-xml/176249-system-xml-xmldocument-parses-well-formed

http://www.codeguru.com/forum/archive/index.php/t-232348.html

 

特别是MSDN的原文:

http://msdn.microsoft.com/zh-cn/library/system.xml.xmltextreader.normalization(VS.80).aspx

 

这下就明白了,我反序列化的时候没有直接用到XmlTextReader,而Normalization默认是true,而是用的StringReader把字符串读取为流,只要把反序列化的方法稍微改改就行:

 

 

好了,完事大吉!

最后奉上测试代码:测试代码

原创粉丝点击