C#でXmlSerializer
C#では public bool ShouldSerialize{PropName}() を実装しておくと、プロパティ化するかどうか選べる。だから例えば空文字列の場合はXMLとして書き出さないといった実装ができる。
以下は辞書データをXMLしたときの例で、色々と細かいことをしている。
[XmlRoot(ElementName = "biblio")]public class BiblioArticle : Article{ [XmlElement(ElementName = "articleEntry")] public BookSource Article { get; set; }}
[XmlRoot(ElementName = "link")]public class BoljArticle : Article{ public class ArticleEntry { [XmlAttribute(AttributeName = "type")] public string Type { get; set; }
[XmlAttribute(AttributeName = "id")] public string ID { get; set; } }}
public class BookSource{ [XmlAttribute(AttributeName = "id")] public string ArticleID { get; set; }
[XmlAttribute(AttributeName = "type")] public string ArticleType { get; set; }
[XmlArray(ElementName = "books")] [XmlArrayItem(ElementName = "book")] public BookEntry[] Entries { get; set; }}
public class BookEntry{ [XmlAttribute(AttributeName = "bookId")] public string ID { get; set; }
[XmlElement(ElementName = "title")] public BookTitle Title { get; set; }
[XmlArray(ElementName = "authors")] [XmlArrayItem(ElementName = "author")] public BookAuthor[] Authors { get; set; }
[XmlElement(ElementName = "publisher")] public string Publisher { get; set; }
[XmlElement(ElementName = "publishedDate")] public YearMonth Date { get; set; }
public bool ShouldSerializeDate() { return Date != null; }
[XmlElement(ElementName = "bookNumber")] public BookNumber BookNumber { get; set; }
[XmlAttribute(AttributeName = "isKids")] public bool IsKids { get; set; }
public bool ShouldSerializeIsKids() { return IsKids; }
[XmlAttribute(AttributeName = "dispOrder")] public int DisplayOrder { get; set; }}
public class BookTitle{ [XmlText] public string Title { get; set; }
[XmlAttribute(AttributeName = "ruby")] public string Ruby { get; set; }
public bool ShouldSerializeTitle() { return !string.IsNullOrEmpty(Ruby); }}
public class YearMonth{ [XmlElement(ElementName= "year")] public int Year { get; set; }
[XmlIgnore] public Month Month { get; set; }}