.NET序列化:将类映射到元素和属性到属性的最佳实践?

时间:2010-10-23 05:34:08

标签: c# .net xml-serialization

我正在尝试序列化以下对象:

[XmlRoot("book")]
public class Book
{
    #region Properties
    [XmlAttribute("isbn-10")]
    public string Isbn10 { get; set; }
    [XmlAttribute("isbn-13")]
    public string Isbn13 { get; set; }
    [XmlAttribute("title")]
    public string Title { get; set; }
    [XmlAttribute("author")]
    public string Author { get; set; }
    [XmlAttribute("collaborator")]
    public string Collaborator { get; set; }
    [XmlAttribute("publisher")]
    public string Publisher { get; set; }
    [XmlAttribute("publication")]
    public DateTime? Publication { get; set; }
    [XmlAttribute("pages")]
    public int Pages { get; set; }
    [XmlAttribute("instock")]
    public bool InStock { get; set; }
    #endregion

    #region Constructors
    public Book (string isbn10, string title, string author, string publisher, DateTime publication, int pages, bool instock=true, string isbn13="N/A", string collaborator="N/A")
    {
        this.Isbn10 = isbn10;
        this.Isbn13 = isbn13;
        this.Author = author;
        this.Collaborator = collaborator;
        this.Publisher = publisher;
        this.Publication = publication;
        this.Pages = pages;
        this.InStock = instock;
    }

    public Book ()
    {
        // To be serialized by an XmlSerializer object, a class must have a default constructor.
        // For additional information about XML Serialization Considerations, visit the following
        // Microsoft Web site: http://msdn2.microsoft.com/en-us/library/182eeyhh(vs.71).aspx
    }
    #endregion
}

尝试将对象实现为元素和属性属性类策略,但正如您可能会注意到的那样,结果显示我并不完全存在,因为编译器正确阻止我设置[XmlElement("book")]类的Book属性。

<?xml version="1.0" encoding="utf-16"?>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            isbn-10="1577315936"
            isbn-13="N/A"
            author="Joseph Campbell"
            collaborator="N/A"
            publisher="New World Library"
            publication="2008-07-28T00:00:00"
            pages="432"
            instock="true"
/>

我考虑创建一个让我们说List<Book>的对象,明显的想法是有一个<books >根元素来序列化,但一方面我不太确定这是否真的有效,另一方面,它可能会使序列化类型依赖于实际实现。

我真的很感激你们可能认为有帮助的任何建议,包括更改序列化策略等等。

非常感谢,

1 个答案:

答案 0 :(得分:3)

您可以(例如)使用容器对象来控制“书籍”。

[XmlRoot("books"), XmlType("books")]
public class Library
{
    private readonly List<Book> books;
    [XmlElement("book")]
    public List<Book> Books {get{return books;}}
}

另一个选项(两个级别)是XmlArray / XmlArrayItem。