问题
I am working with XML serialization, I am doing good so far. 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.
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);
}
回答1:
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.
回答2:
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.
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(',');
}
}
}
来源:https://stackoverflow.com/questions/25406163/serialize-list-of-strings-as-an-attribute