0

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>
2
  • Will Holder only have the array of Things? Commented Sep 14, 2011 at 0:25
  • @Austin No, it would have other elements. Let me update the example. Commented Sep 14, 2011 at 0:27

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't that just wrap Thing in another Thing tag?
@MPelletier nope. look at the example in the linked msdn page or just give it a try.
OK, I thought XmlElement was a way to rename the tag. Silly me. I haven't actually seen it in action. I'll check the page AND try it. :)
Wow, it renames the tag in every other context, but with arrays, it just renames the elements, not the array! Nice! Now to read up!
0

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?

Comments

0

Use the [XmlElement] attribute:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.