我正在阅读此file并使用System.Xml.Serialization.XmlSerializer进行序列化和反序列化。抱歉,我无法在此问题中发布文件内容,因为StackOverflow正在对它们进行错误编码。
Deserialize函数抛出异常。
'',十六进制值0x03,是无效字符。第5行,第20位。
我做错了什么?
这是我的代码。也可用here
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace XMLTester
{
public class HexTester
{
public static void Main(string[] args)
{
var lines = File.ReadAllLines(@"..\..\HexText.txt"); ;
var foo = new Foo()
{
Items = new List<FooBar>()
{
new FooBar()
{
Text = lines[0]
}
}
};
string xml = SerializeToXML(foo);
var objTabs = DeserializeFromXML(xml, typeof(Foo)); //This throws an error
}
static string SerializeToXML(object obj)
{
StringBuilder xml = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
TextWriter textWriter = new StringWriter(xml);
serializer.Serialize(textWriter, obj);
textWriter.Close();
return xml.ToString();
}
static object DeserializeFromXML(string xml, Type toType)
{
XmlSerializer deserializer = new XmlSerializer(toType);
TextReader textReader = new StringReader(xml);
Object obj = deserializer.Deserialize(textReader); //This throws an error
textReader.Close();
return obj;
}
}
public class Foo
{
public List<FooBar> Items { get; set; }
}
public class FooBar
{
public string Text { get; set; }
}
}
答案 0 :(得分:1)
0x03(End-of-Text character)只是not an allowed character in XML。
因此,在序列化或反序列化之前,您需要clean the invalid characters。