RiddlerDev
RiddlerDev

Reputation: 7439

XML Object Serialization on Collection At Root Level

Trying to deserialize an XML file from a 3rd party tool into a custom software class. The problem is that the XML is a little goofy as the "root" item is really the declaration of the collection. I have done a lot with XMLArray and other definitions to define serialization, but this does not seem to work. The best I have been able to do is to get the collection read in but none of the objects in the collection are initialized with the variables.

Here is an example of what I am facing:

XML:

<Animals>
  <Animal>
    <Name>Mr. Cow</Name>
    <Type>Cow</Type>
  </Animal>
  <Animal>
    <Name>Belle</Name>
    <Type>Cow</Type>
  </Animal>
  <Animal>
    <Name>Porky</Name>
    <Type>Pig</Type>
  </Animal>
</Animals>

I then have my XMLRoot defined as "Animals" in my "Farm" object. And have a list property for my class of "Animal". If I define that property (list AnimalCollection) the best I can get is a list of 3 uninitiated Animal objects (none of the values set).

Around the office, the best we could figure to do was to add a node to the file as a stream before trying to deserialize it and use it business as usual, but obviously this seems like a horrible hack. Hoping that there is a better way that I am just missing.

I have also thought about manually reading the document as well... but again hoping there is a more elegant way.

Upvotes: 2

Views: 274

Answers (1)

Josh
Josh

Reputation: 913

XmlSerializer serializer = new XmlSerializer(typeof(Animal[]), new XmlRootAttribute("Animals"));

public class Animal
{
    [XmlElement]
    public string Name;
    [XmlElement]
    public string Type;
}

Upvotes: 3

Related Questions