我有一个可以为空的int类?数据类型设置为序列化为xml元素.有没有办法设置它,所以如果值为null,xml序列化程序将不会序列化该元素?
我试图添加[System.Xml.Serialization.XmlElement(IsNullable = false)]属性,但我得到一个运行时序列化异常,说有一个反映类型的错误,因为"IsNullable可能不会设置为'false '对于Nullable类型.考虑使用'System.Int32'类型或从XmlElement属性中删除IsNullable属性."
[Serializable]
[System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")]
public class Score
{
private int? iID_m;
...
/// <summary>
///
/// </summary>
public int? ID
{
get
{
return iID_m;
}
set
{
iID_m = value;
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
上面的类将序列化为:
<Score xmlns="http://mycomp.com/test/score/v1">
<ID xsi:nil="true" />
</Score>
Run Code Online (Sandbox Code Playgroud)
但对于null的ID,我根本不需要ID元素,主要是因为当我在MSSQL中使用OPENXML时,对于看起来像的元素,它返回0而不是null
我从第三方获得了一个xml,我需要将它反序列化为C#对象.此xml可能包含值为整数类型或空值的属性:attr ="11"或attr ="".我想将此属性值反序列化为类型为可空整数的属性.但XmlSerializer不支持反序列化为可空类型.在使用InvalidOperationException创建XmlSerializer期间,以下测试代码失败{"有一个错误反映了类型'TestConsoleApplication.SerializeMe'."}.
[XmlRoot("root")]
public class SerializeMe
{
[XmlElement("element")]
public Element Element { get; set; }
}
public class Element
{
[XmlAttribute("attr")]
public int? Value { get; set; }
}
class Program {
static void Main(string[] args) {
string xml = "<root><element attr=''>valE</element></root>";
var deserializer = new XmlSerializer(typeof(SerializeMe));
Stream xmlStream = new MemoryStream(Encoding.ASCII.GetBytes(xml));
var result = (SerializeMe)deserializer.Deserialize(xmlStream);
}
}
Run Code Online (Sandbox Code Playgroud)
当我将'Value'属性的类型更改为int时,反序列化失败并出现InvalidOperationException:
XML文档中存在错误(1,16).
任何人都可以建议如何将具有空值的属性反序列化为可空类型(作为null),同时将非空属性值反序列化为整数?有没有任何技巧,所以我不必手动对每个字段进行反序列化(实际上有很多)?
来自ahsteele的评论后更新:
据我所知,此属性仅适用于XmlElementAttribute - 此属性指定元素没有内容,无论是子元素还是正文.但我需要找到XmlAttributeAttribute的解决方案.无论如何我不能改变xml,因为我无法控制它.
仅当属性值为非空或缺少属性时,此属性才有效.当attr具有空值(attr ='')时,XmlSerializer构造函数失败(如预期的那样).
public class Element
{
[XmlAttribute("attr")]
public int Value { get; …Run Code Online (Sandbox Code Playgroud)