I have the following C# classes :
public class Books
{
public List<Book> BookList;
}
public class Book
{
public string Title;
public string Description;
public string Author;
public string Publisher;
}
How can I serialize this class into the following XML?
<Books>
<Book Title="t1" Description="d1"/>
<Book Description="d2" Author="a2"/>
<Book Title="t3" Author="a3" Publisher="p3"/>
</Books>
I want the XML to have only those attributes whose values are not null/empty. For example: In the first Book element, author is blank, so it should not be present in the serialized XML.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.
XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.
Remarks. The XmlIgnoreAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. If you apply the XmlIgnoreAttribute to any member of a class, the XmlSerializer ignores the member when serializing or deserializing an instance of the class.
You should be able to use the ShouldSerialize*
pattern:
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);
}
}
Alternative :
DefaultValueAttribute
attributeContentPropertyAttribute
attributeYou end up with something like this:
[ContentProperty("Books")]
public class Library {
private readonly List<Book> m_books = new List<Book>();
public List<Book> 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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With