条件xml序列化
我有以下C#类:
public class Books { public List BookList; } public class Book { public string Title; public string Description; public string Author; public string Publisher; }
如何将此类序列化为以下XML?
我希望XML只包含那些值为null / empty的属性。 例如:在第一个Book元素中,author是空白的,因此它不应出现在序列化XML中。
您应该能够使用ShouldSerialize*
模式:
public class Book { [XmlAttribute] public string Title {get;set;} public bool ShouldSerializeTitle() { return !string.IsNullOrEmpty(Title); } [XmlAttribute] public string Description {get;set;} public bool ShouldSerializeDescription() { return !string.IsNullOrEmpty(Description ); } [XmlAttribute] public string Author {get;set;} public bool ShouldSerializeAuthor() { return !string.IsNullOrEmpty(Author); } [XmlAttribute] public string Publisher {get;set;} public bool ShouldSerializePublisher() { return !string.IsNullOrEmpty(Publisher); } }
替代方案
- 将您的公共字段切换为属性
- 使用
DefaultValueAttribute
属性定义默认值 - 使用
ContentPropertyAttribute
属性定义内容属性 - 使用XamlWriter / XamlReader
你最终得到这样的东西:
[ContentProperty("Books")] public class Library { private readonly List m_books = new List (); public List Books { get { return m_books; } } } public class Book { [DefaultValue(string.Empty)] public string Title { get; set; } [DefaultValue(string.Empty)] public string Description { get; set; } [DefaultValue(string.Empty)] public string Author { get; set; } }
public class Books { [XmlElement("Book")] public List BookList; } public class Book { [XmlAttribute] public string Title; [XmlAttribute] public string Description; [XmlAttribute] public string Author; [XmlAttribute] public string Publisher; } class Program { static void Main() { var books = new Books { BookList = new List (new[] { new Book { Title = "t1", Description = "d1" }, new Book { Author = "a2", Description = "d2" }, new Book { Author = "a3", Title = "t3", Publisher = "p3" }, }) }; var serializer = new XmlSerializer(books.GetType()); serializer.Serialize(Console.Out, books); } }
如果要从根节点中删除命名空间:
var namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); serializer.Serialize(Console.Out, books, namespaces);
另外,我建议您使用属性而不是模型类中的字段来更好地封装:
public class Books { [XmlElement("Book")] public List BookList { get; set; } }