C# 将字符串列表序列化为属性
我正在处理XML序列化,到目前为止我做得很好。然而,我遇到了一个问题,我希望你们能帮我解决这个问题 我的课程如下:C# 将字符串列表序列化为属性,c#,xml,list,serialization,C#,Xml,List,Serialization,我正在处理XML序列化,到目前为止我做得很好。然而,我遇到了一个问题,我希望你们能帮我解决这个问题 我的课程如下: public class FrameSection { [XmlAttribute] public string Name { get; set; } [XmlAttribute] public string[] StartSection { get; set; } } using (var fileStream = new System.IO.
public class FrameSection
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string[] StartSection { get; set; }
}
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);
}
序列化时,我得到了类似的结果:
<FrameSection Name="VAR1" StartSection="First circle Second circle"/>
您可以在序列化过程中忽略数组(仅将其用作备份存储),并添加将被序列化和反序列化的属性:
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(','); }
}
}
我在这里使用逗号作为数组项分隔符,但您可以使用任何其他字符。您可以在序列化过程中忽略数组(仅将其用作后备存储),并添加一个将被序列化和反序列化的属性:
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(',');
}
}
}
我不知道有什么方法可以更改数组的序列化行为,但是如果您对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(',');
}
}
}
很好的解决方案。我建议OP尝试使用一些不可打印的字符,以避免错误地拼接字符串。很好的一个,它肯定会解决我的问题,但我认为应该将其添加到XmlAttributeClassNice解决方案中。我建议OP尝试使用一些不可打印的字符,以避免错误地拼接字符串。不错,这肯定会解决我的问题,但我认为应该将其添加到XmlAttributeClass中。我认为您应该为“StartSection”属性添加[XmlIgnore],这是不必要的。指定的类设计会产生期望的结果。我认为应该为“StartSection”属性添加[XmlIgnore],这是不必要的。指定的类设计会产生所需的结果。