我傳遞了一個xml文檔,其中缺少一些屬性給開發者。我需要缺少的值在結果對象中爲null,但是當前將反序列化爲零,將bools設爲false。XML將空屬性反序列化爲零併爲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; }
}
}
我看過那個。似乎沒有任何工作可以對空屬性進行反序列化。你能告訴我什麼具體我正在尋找與我的例子有關。謝謝 – Jules
這個[XmlElementAttribute(IsNullable = false)]似乎在串行化到xml時不起作用,但不是從它反序列化。 – Jules
此屬性在deserilising時不起作用。我試過[XmlAttribute,DefaultValue(null)],這也沒有任何影響。 – Jules