是否有一个属性可以跳过c#的xml序列化中的空数组?(Is there an attribute to skip empty arrays in the xml

系统教程 行业动态 更新时间:2024-06-14 16:59:47
是否有一个属性可以跳过c#的xml序列化中的空数组?(Is there an attribute to skip empty arrays in the xml-serialization of c#?)

是否有一个属性可以跳过c#的xml序列化中的空数组? 这会增加xml输出的可读性。

Is there an attribute to skip empty arrays in the xml-serialization of c#? This would increase human-readability of the xml-output.

最满意答案

那么,你可以添加一个ShouldSerializeFoo()方法:

using System; using System.ComponentModel; using System.Xml.Serialization; [Serializable] public class MyEntity { public string Key { get; set; } public string[] Items { get; set; } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool ShouldSerializeItems() { return Items != null && Items.Length > 0; } } static class Program { static void Main() { MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] }; XmlSerializer ser = new XmlSerializer(typeof(MyEntity)); ser.Serialize(Console.Out, obj); } }

ShouldSerialize{name} patten被识别,并调用该方法以查看是否在序列化中包含该属性。 还有一个替代的{name}Specified模式,它允许您在反序列化时(通过setter)检测事物:

[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [XmlIgnore] public bool ItemsSpecified { get { return Items != null && Items.Length > 0; } set { } // could set the default array here if we want }

Well, you could perhaps add a ShouldSerializeFoo() method:

using System; using System.ComponentModel; using System.Xml.Serialization; [Serializable] public class MyEntity { public string Key { get; set; } public string[] Items { get; set; } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool ShouldSerializeItems() { return Items != null && Items.Length > 0; } } static class Program { static void Main() { MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] }; XmlSerializer ser = new XmlSerializer(typeof(MyEntity)); ser.Serialize(Console.Out, obj); } }

The ShouldSerialize{name} patten is recognised, and the method is called to see whether to include the property in the serialization. There is also an alternative {name}Specified pattern that allows you to also detect things when deserializing (via the setter):

[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [XmlIgnore] public bool ItemsSpecified { get { return Items != null && Items.Length > 0; } set { } // could set the default array here if we want }

更多推荐

本文发布于:2023-04-17 09:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d342fbeeac17f7d375976063f268734e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   跳过   有一个   属性   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!