Is it possible to deserialize xml to List object using .net provided serialization attributes?
I have xml input which looks like (simplified version used for example):
<Student>
<Subject> History </Subject>
<Subject> English </Subject>
</Student>
Is there a way to get the above xml deserialized to a object whose class looks like:
[Serializable]
[XmlRoot(ElementName = "Student", Namespace="")]
class Student
{
public Student()
{
Subject = new List<string>();
}
public List<string> Subject {get;set;}
}
Note I am trying to figure out if this can be done without having to开发者_C百科 implement IXmlSerializable interface, and I want to use a list to store the Subject values (not a string [] which I know is possible is I use the XmlElement attribute).
Decorate the Subject property with the XmlArrayAttribute.
[XmlArray]
public List<string> Subject { get; set; }
If you need to omit the Subject element and have the Subject entries directly below Student, you can simply use the [XmlElement] attribute:
[XmlElement]
public List<string> Subject { get; set; }
Serializing this with the Student class produces output similar to this:
<?xml version=\"1.0\" encoding=\"utf-16\"?>
<Student xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<Subject>History</Subject>
<Subject>English</Subject>
</Student>"
精彩评论