views:

61

answers:

1

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 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).

+3  A: 

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\"&gt;
    <Subject>History</Subject>
    <Subject>English</Subject>
</Student>"
Mark Seemann
Can you still use a list for this? I thought it throws an error unless it is serializing to an array.
NickLarsen
I have already tried that. It doesn't seem to work!
jvtech
Actually you are right, "You can also apply it to collections and fields that return an ArrayList or any field that returns an object that implements the IEnumerable interface." http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayattribute.aspx
NickLarsen
According to the documentation, it works with anything that implements IEnumerable. IIRC, this is correct, but it's been a while...
Mark Seemann
it doesn't work with XmlArray attribute.. i am guessing for now will just change this to an array and decorate the field with XmlElement attribute...
jvtech
Yes, it *does* work (I just checked), but I've edited my answer to include more options.
Mark Seemann
It should work with a list and with `[XmlElement]`
John Saunders
+1 for the XmlElement attribute. That worked in my environment. FWIW, the XmlArray attribute didn't work for me either.
Austin Salonen
Thanks Mark.. using XmlElement does work on the LIST.. I thought I had tried that before, and was not getting it to work.. must be doing something else wrong..
jvtech