序列化字符串列表作为属性

时间:2014-08-20 13:34:22

标签: c# xml list serialization

我正在使用XML序列化,到目前为止我做得很好。但是,我偶然发现了一个问题,我希望你们能帮助我。

我有一个课程如下:

public class FrameSection
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlAttribute]
    public string[] StartSection { get; set; }
}

序列化后,我得到了类似的东西:

<FrameSection Name="VAR1" StartSection="First circle Second circle"/>

问题在于反序列化,我有四个项而不是两个,因为空格用作分隔符,我想知道我是否可以使用不同的分隔符。

注意:我知道我可以删除[XmlAttribute]来解决问题,但我更喜欢这种结构,因为它更紧凑。

序列化代码如下:

using (var fileStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Create))
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ModelElements));
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.Encoding = Encoding.UTF8;
    settings.CheckCharacters = false;
    System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(fileStream, settings);
    serializer.Serialize(writer, allElements);
}

2 个答案:

答案 0 :(得分:3)

您可以在序列化期间忽略数组(只是将其用作后备存储),并添加一个将被序列化和反序列化的属性:

public class FrameSection
{
   [XmlAttribute]
   public string Name { get; set; }

   [XmlIgnore]
   public string[] StartSection { get; set; }

   [XmlAttribute("StartSection")]
   public string StartSectionText
   {
      get { return String.Join(",", StartSection); }
      set { StartSection = value.Split(','); }
   }
}

我在这里使用逗号作为数组项分隔符,但您可以使用任何其他字符。

答案 1 :(得分:0)

我不知道如何更改数组的序列化行为,但是如果对FrameSection类进行以下更改,则应该获得所需的行为。

public class FrameSection
{
    [XmlAttribute]
    public string Name { get; set; }

    public string[] StartSection { get; set; }

    [XmlAttribute]
    public string SerializableStartSection
    {
        get
        {
            return string.Join(",", StartSection);
        }

        set
        {
            StartSection = value.Split(',');
        }
    }
}