如何基于通用列表属性进行条件xml序列化

时间:2015-07-23 06:45:05

标签: c# xml-serialization

我有以下课程

public class Books
{
    public Books()
    {
        BookList = new List<Book>();
    }
    public Customer Customer { get; set; }
    public List<Book> BookList { get; set; }
    public bool ShouldSerializeBookList(){
        -- serialize only when the particular book selected property is true--
    }
}

public class Book
{
    public string Title { get; set; }
    public bool Selected { get; set; }
}

考虑我有三本书,标题为t1,t2,t3。但只选择了t1和t3。

那么如何根据每本书的Selected属性将这个类序列化为以下xml?

<Books> <Book Title="t1" /> <Book Title="t3" /> </Books>

1 个答案:

答案 0 :(得分:0)

我可以建议您添加可根据任何过滤规则自定义的过滤器。查看您的旗帜是一种特殊情况。 代码注释中的解释:

public class Books
    {
        public Books()
        {

        }

        // apply this function each time befor doing serialization
        public void RunBeforeSerialization(Func<Book, bool> filter)
        {
            booksFilter = filter;
        }

        // this is the filter that you set before serialization
        Func<Book, bool> booksFilter = null;

        public string Customer { get; set; }

        List<Book> bookList = new List<Book>();
        public List<Book> BookList
        {
            get
            {
                if (booksFilter == null) // the regular property usage
                {
                    return bookList;
                }
                else // used when serialize
                {
                    var temp = from book in bookList
                              where booksFilter(book) // applying the filter
                              select book;

                    var res = temp.ToList();
                    booksFilter = null;
                    return res;
                }
            }
            set
            {
                bookList = value;
            }
        }
    }

这是主要功能:

static void Main(string[] args)
        {
            Books books = new Books() { Customer = "Allan" };
            books.BookList.Add(new Book() { Title = "T1", Selected = true });
            books.BookList.Add(new Book() { Title = "T2", Selected = false });
            books.BookList.Add(new Book() { Title = "T3", Selected = true });

            // here you add the filter that used when serialized
            books.RunBeforeSerialization(b => b.Selected == true);

            XmlSerializer ser = new XmlSerializer(typeof(Books));
            StringWriter sw = new StringWriter();
            ser.Serialize(sw, books);

            Console.WriteLine(sw.ToString());

            Console.ReadLine();

        }

您可以了解如何设置过滤的任何其他方式,但这里的主要思想是为用户提供控制序列化期间返回的内容的选项,而不会损害常规属性的使用。