[英]Serialize list of strings as an attribute
我正在使用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);
}
您可以在序列化期間忽略數組(僅將其用作后備存儲),並添加將被序列化和反序列化的屬性:
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(','); }
}
}
我在這里使用逗號作為數組項分隔符,但您可以使用任何其他字符。
我不知道改變數組的序列化行為的方法,但是如果對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.