MPelletier
MPelletier

Reputation: 16657

Serialize elements of an array but not the array (XMLSerizlization)

I have a simple array that I need to serialize as part of a larger object.

public class Holder
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Thing[] Thingies { get; set; }
}

public class Thing {}

Normally this would be serialized as:

...
<Holder>
    <ID>...</ID>
    <Name>...</Name>
    <ArrayOfThing>
        <Thing>...</Thing>
        <Thing>...</Thing>
        <Thing>...</Thing>
        ...
    </ArrayOfThing>
</Holder>

Without worrying too much about deserialization, is there a way I could simply remove the ArrayOf element, but keep the elements inside, so that I'd have:

...
<Holder>
    <ID>...</ID>
    <Name>...</Name>
    <Thing>...</Thing>
    <Thing>...</Thing>
    <Thing>...</Thing>
    ...
</Holder>

Upvotes: 0

Views: 384

Answers (3)

gilly3
gilly3

Reputation: 91467

Use the [XmlElement] attribute:

[XmlElement]
public Thing[] Thingies { get; set; }  

Upvotes: 0

Bernie White
Bernie White

Reputation: 5075

You could implement IXmlSerializable to let you read and write Thing or other children from the containing XML element.

Here is how you would implement this Proper way to implement IXmlSerializable?

Upvotes: 0

Bala R
Bala R

Reputation: 108937

Try

public class Holder
{
    public int ID { get; set; }
    public string Name { get; set; }

    [XmlElement("Thing")]
    public Thing[] Thingies { get; set; }
}

MSDN for XmlElementAttribute has some examples as well.

Upvotes: 2

Related Questions