有条件的XML序列化 [英] Conditional xml serialization
本文介绍了有条件的XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的C#类:
public class Books
{
public List<Book> BookList;
}
public class Book
{
public string Title;
public string Description;
public string Author;
public string Publisher;
}
我如何序列化这个类为以下XML?
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>
我希望XML有其唯一的值不为空/空的属性。
例如:在第一个Book元素,作者是空白的,所以它不应该在序列化的XML present
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.
推荐答案
您应该可以使用 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);
}
}
这篇关于有条件的XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文