提问人:Doctor Blue 提问时间:9/25/2023 最后编辑:Doctor Blue 更新时间:9/25/2023 访问量:55
C# XML 序列化:将可为 null 的值类型网格化(想要禁止显示没有装饰器/属性/ShouldSerialize 的“null”值)
C# XML Serialization: Seralizizing Nullable Value Types (Want to Suppress "null" Values Without Decorators/Attributes/ShouldSerialize)
问:
我正在使用 C# 中的代码,试图将对象序列化为 XML。我无法将XML属性或额外属性(例如bool ShouldSerializeFoo
)添加到此对象。我也不能向属性添加任何属性。我只能控制 XML 序列化程序。[Xml*]
一些属性是可为 null 的类型(等),如果它们为 null(即 是假的)。int?
foo.HasValue
有没有办法指示 C# 中的 XML 序列化程序跳过可为 null 的值类型的 null 属性?如果没有,有没有办法为每个属性挂钩,以便我可以将自定义逻辑注入其中?(我可以手动检查该值是否为可空类型并自己检查)。ShouldSerialize()
HasValue
给定此 C# 类:
public class SomeObject
{
public int? Foo { get; set; }
public string? Bar { get; set; }
}
如果我设置为 和 ,我希望XML输出为:Foo
null
Bar
"Something"
<SomeObject>
<Bar>Something</Bar>
</SomeObject>
我目前正在使用这样的东西来调用序列化程序:
using System.Xml;
using System.Xml.Serialization;
// Class code omitted
public string CreateXML(SomeObject objToSerialize)
{
XmlSerializer xmlSerializer = new(objToSerialize.GetType());
using StringWriter stringWriter = new();
using XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new() { OmitXmlDeclaration = true });
xmlSerializer.Serialize(xmlWriter, objToSerialize, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
return stringWriter.ToString();
}
如果我想要的是不可能的,我将求助于事后手动编辑序列化的 XML 以删除它们(正则表达式来查找和替换带有空字符串的元素),但我宁愿序列化程序首先跳过这些值。'nil'
答: 暂无答案
评论
XmlAttributeOverrides
只允许您指定属性重写(而不是方法),因此无法使用任何属性重写来执行此操作。[XmlElement(IsNullable = false)]
public int? Foo { get; set; }
IsNullable may not be set to 'false' for a Nullable<System.Int32> type
ShouldSerialize()
XmlAttributeOverrides
XmlWriter
XmlTextWriter
XElement
string
XElement
CDATA