【问题标题】:Serialize list of strings as an attribute将字符串列表序列化为属性
【发布时间】:2014-08-20 13:34:22
【问题描述】:

我正在使用 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);
}

【问题讨论】:

    标签: c# xml list serialization


    【解决方案1】:

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

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

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

    【讨论】:

    • 不错的解决方案。我建议 OP 他尝试使用一些不可打印的字符来避免错误地拼接字符串。
    • 不错,肯定能解决我的问题,但我认为应该添加到XmlAttributeClass中
    【解决方案2】:

    我不知道如何更改数组的序列化行为,但如果您对 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(',');
            }
        }
    }
    

    【讨论】:

    • 我相信您应该为“StartSection”属性添加 [XmlIgnore]
    • 没必要。指定的类设计产生了预期的结果。
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多