终于把自已恶搞一把,平时图省劲用山寨客户端向服务器提交数据,数据编码一直有问题。鄙人负责服务器的WCF接口开发,于是有一天测试WCF时填了自己的用户名,接下来报错
(十六进制值 0x00)是无效的字符 ,报应啊。
我首先是把WCF返回的对象序列化一下,存入数据库。需要时反序列化,结果有些编码不对的对象在这时出了问题。百度了一些国内的解决方法,例如替换
'\0'或者写函数过滤,都解决不了问题。只能求助google中的英文资料了,结果是一很简单的事,用xmlTextReader把stringReader包装一下即可。
总结,各类山寨客户端是测试的神器。好多错误信息抱的是中文错误,找不到中文资料时想法找到这个错误描述的英文原文,google之。
两种解决方法代码如下:
引用自http://baleinoid.com/whaly/2011/08/xml-deserialization-invalid-character/
Here is an example :
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
public
class
MyObject
{
public
string
MyString {
get
;
set
; }
}
class
Program
{
static
void
Main(
string
[] args)
{
XmlSerializerFactory fact =
new
XmlSerializerFactory();
XmlSerializer ser = fact.CreateSerializer(
typeof
(MyObject));
MyObject obj0 =
new
MyObject();
obj0.MyString =
"Hello\0World"
;
// Serialize the object
StringWriter sw =
new
StringWriter();
ser.Serialize(sw, obj0);
string
xml = sw.ToString();
// We can check that in the xml a \0 is transformed in
Console.WriteLine(xml);
// Classic use of XmlReader.Create
StringReader sr1 =
new
StringReader(xml);
XmlReader xr1 = XmlTextReader.Create(sr1);
// xr1's type is XmlTextReaderImpl
try
{
MyObject obj1 = (MyObject)ser.Deserialize(xr1);
Console.WriteLine(
"XmlReader [CheckCharacters({0})] : Success : {1}"
, xr1.Settings.CheckCharacters, obj1.MyString);
Console.WriteLine(obj1.MyString);
}
catch
(Exception e)
{
Console.WriteLine(
"XmlReader [CheckCharacters({0})] : Error : {1}"
, xr1.Settings.CheckCharacters, e.InnerException);
}
// Using an XmlTextReader
StringReader sr2 =
new
StringReader(xml);
XmlTextReader xr2 =
new
XmlTextReader(sr2);
// xr2.Settings is null
MyObject obj2 = (MyObject)ser.Deserialize(xr2);
Console.WriteLine(
"XmlTextReader : Success : {0}"
, obj2.MyString);
// Using XmlReader with the good XmlReaderSettings
StringReader sr3 =
new
StringReader(xml);
XmlReaderSettings settings =
new
XmlReaderSettings();
settings.CheckCharacters =
false
;
// default value is true;
XmlReader xr3 = XmlTextReader.Create(sr3, settings);
// xr3.Settings.CheckCharacters is a read only and xr3's type is XmlTextReaderImpl
MyObject obj3 = (MyObject)ser.Deserialize(xr3);
Console.WriteLine(
"XmlReader [CheckCharacters({0})] : Success : {1}"
, xr3.Settings.CheckCharacters, obj3.MyString);
}
}
|