简体   繁体   English

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

[英]Serialize list of strings as an attribute

I am working with XML serialization, I am doing good so far. 我正在使用XML序列化,到目前为止我做得很好。 However, I stumbled with a problem and I wish if you guys can help me with it. 但是,我偶然发现了一个问题,我希望你们能帮助我。

I have a class as following: 我有一个课程如下:

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

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

When serialized, I got something like that: 序列化时,我得到了类似的东西:

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

The problem is with deserialization, I got four items rather than two as space is used as delimiter, I wonder if I can use different delimiter. 问题是反序列化,我有四个项而不是两个,因为空格用作分隔符,我想知道我是否可以使用不同的分隔符。

Note: I know I can remove [XmlAttribute] to solve the problem, but I prefer this structure because it is more compact. 注意:我知道我可以删除[XmlAttribute]来解决问题,但我更喜欢这种结构,因为它更紧凑。

The serialization code as following: 序列化代码如下:

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);
}

You can ignore array during serialization (just use it as backing store), and add a property which will be serialized and deserialized: 您可以在序列化期间忽略数组(仅将其用作后备存储),并添加将被序列化和反序列化的属性:

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(','); }
   }
}

I used here comma as a array items separator, but you can use any other character. 我在这里使用逗号作为数组项分隔符,但您可以使用任何其他字符。

I'm unaware of a way to change the serialization behavior of an array, but if you make the following change to your FrameSection class you should get the desired behavior. 我不知道改变数组的序列化行为的方法,但是如果对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(',');
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM