【发布时间】:2010-10-23 05:34:07
【问题描述】:
我正在尝试序列化以下对象:
[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 > 根元素进行序列化,但一方面我不太确定这是否真的有效,另一方面它可能会使序列化依赖于实际的实现。
非常感谢你们认为可能有帮助的任何建议,包括更改序列化策略等。
非常感谢,
【问题讨论】:
-
顺便说一句;您询问整体策略 - XML 是必需的吗?热
-
嗨,马克,非常感谢您花时间回复。 XML目前是一个要求,属性是回去的方式,因为这样的XML“摘要”是丰富的——在某些时候,我考虑不“暗示”序列化程序,因此让它对元素进行“常规”序列化然后做一些文件压缩,但在接收端重构解析不是一种选择。
标签: c# .net xml-serialization