我經常這樣做。我通常使用頂級類來封裝集合屬性作爲成員,並且與xml文件具有一對一的關係。該類的成員可以是集合或簡單的屬性等
這裏是有自定義對象的集合的代碼片段:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(ElementName = "DeployRuns", Namespace = "", IsNullable = false)]
public class DeployRuns : List<RunDetail>
{
,然後如果你想封裝在另一個類中您的收藏這將序列化,看到這個類的底部性質:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class DeployDetails
{
public DeployDetails()
{
this.DeployRuns = new DeployRuns();
}
[System.Xml.Serialization.XmlAttributeAttribute("sourcePath")]
public string SourcePath { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute("archiveDestinationPath")]
public string ArchiveDestinationPath { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute("databaseDestinationPath")]
public string DatabaseDestinationPath { get; set; }
public DeployRuns DeployRuns { get; set; }
}
而且玩完了代碼示例,這是我這個層次結構的頂層類:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(ElementName = "ExecutionHistory", Namespace = "", IsNullable = false)]
public class ExecutionHistory
{
public ExecutionHistory()
{
this.CaptureDetails = new CaptureDetails();
this.DeployDetails = new DeployDetails();
}
[XmlElementAttribute("CaptureDetails", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public CaptureDetails CaptureDetails { get; set; }
[XmlElementAttribute("DeployDetails", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public DeployDetails DeployDetails { get; set; }
不知道最終目標很難回答。這是因爲如果您將多個對象序列化爲一個文件並且彼此相鄰,那麼將創建的文檔將不會是有效的Xml文檔,因爲它將具有多個根元素。請注意,這是一個有效的場景,但我不確定這是否是您想要的。 – Pawel 2012-02-17 17:59:20