我有一个我们序列化和反序列化的对象。在序列化对象时,我们动态添加名称空间,该名称空间在类定义中不存在作为属性。我在这里创建了一个小例子来重复这个问题:
我有一个类,叫做 Person:
[XmlRoot("person")]
public class Person
{
[XmlIgnore]
public DateTime? dob { get; set; }
[XmlAttribute("dobs")]
public DateTime dobser { get{return dob.Value;} set{dob=value;} }
public bool ShouldSerializedobser()
{
return dob.HasValue;
}
[XmlAttribute("name")]
public string Name { get; set; }
public bool ShouldSerializeName()
{
return !string.IsNullOrWhiteSpace(Name);
}
public int? Age { get; set; }
}
这里的代码序列化和反序列化,
public class Program
{
static void Main(string[] args)
{
var person = new Person();
person.Age = 12;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
//add namespace
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("ns1", "http://www.microsoft.com/schema/ml/v1");
XmlSerializer xs = new XmlSerializer(typeof(Person));
xs.Serialize(sw, person,namespaces);
// try to deserialize, it fails. It is working If I don't add namespace
xs.Deserialize(GenerateStreamFromString(sb.ToString()));
Console.WriteLine(sb.ToString());
Console.Read();
}
}
任何帮助将不胜感激