我正在将一个缺少某些属性的 xml 文档传递给解串器。我需要在结果对象中将缺失值设为 null,但当前 ints 反序列化为零并且布尔值设为 false。
下面的示例显示了一个 vals 正确反序列化的文档,但没有 vals 的文档返回了零和空值。
如何强制反序列化器不要像这样处理缺失的属性。
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace SOQuestion
{
class Program
{
static void Main(string[] args)
{
var resultWithVals = getObject(docWithVals());
var resultWithoutVals = getObject(docWithoutVals());
Console.WriteLine("WITH VALS");
Console.WriteLine(resultWithVals.someBool);
Console.WriteLine(resultWithVals.someFloat);
Console.WriteLine(resultWithVals.someInt);
Console.WriteLine(resultWithVals.someString);
Console.WriteLine("WITHOUT VALS"); // nulls are returned here as zero and false
Console.WriteLine(resultWithoutVals.someBool);
Console.WriteLine(resultWithoutVals.someFloat);
Console.WriteLine(resultWithoutVals.someInt);
Console.WriteLine(resultWithoutVals.someString);
Console.ReadLine();
}
public static XmlDocument docWithVals()
{
var doc = new XmlDocument();
var el = (XmlElement)doc.AppendChild(doc.CreateElement("Result"));
el.SetAttribute("someString", "Hello World");
el.SetAttribute("someBool", "true");
el.SetAttribute("someInt", "1");
el.SetAttribute("someFloat", "1.1");
return doc;
}
public static XmlDocument docWithoutVals()
{
var doc = new XmlDocument();
var el = (XmlElement)doc.AppendChild(doc.CreateElement("Result"));
el.SetAttribute("someString", "Hello World");
return doc;
}
public static Result getObject(XmlDocument doc)
{
var mySerializer = new XmlSerializer(new Result().GetType());
var myStream = new MemoryStream();
doc.Save(myStream);
myStream.Position = 0;
var r = mySerializer.Deserialize(myStream);
return (Result)r;
}
}
[Serializable]
public class Result
{
[XmlAttribute]
public string someString { get; set; }
[XmlAttribute]
public bool someBool { get; set; }
[XmlAttribute]
public int someInt { get; set; }
[XmlAttribute]
public float someFloat { get; set; }
}
}