使用序列化在Xml中保存多个项

本文关键字:保存 Xml 序列化 | 更新日期: 2023-09-27 18:25:10

我用如下的序列化程序将onject保存到xml文件中:

        FileStream stream = new FileStream(tempFilename,FileMode.Create);
        XmlSerializer serializer = new XmlSerializer(newType);
        serializer.Serialize(stream,objectname);

但是使用此代码,我只能在xml文件中输入一个项目,如果我在其中插入新项目,它将被覆盖。我如何在文件中输入多个项目?Sholud我用列表吗?

使用序列化在Xml中保存多个项

我经常这样做。我通常使用一个顶级类,它将集合属性封装为成员,并与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; }

如果要将多个项序列化到一个文件中,请使用List<T>数据结构。

注意,T表示的类型(类)必须用[XmlRoot]标记为类属性,或者实现IXmlSerializable

您可以创建一个List类型的对象,然后添加任意数量的"objectname"。然后将该列表传入以进行序列化。