Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XmlSerialization - Serialize collection contents only

Status
Not open for further replies.

KDavie

Programmer
Feb 10, 2004
441
0
0
US

I have some objects that I am serializing that contain collections. The collections are of List type (though I am not opposed to using a different type if it will help me accomplish my goal). When the objects are serialized I would like to serialize the contents of the collection without having it serialize into an XML Array. For example, say I have the following list:

Code:
public class Example
{
    public List<Number> Numbers;

    //Populates Numbers with example data
    private PopulateList()
    {
        Numbers = new List<Number>();
        Numbers.Add(new Number(1));
        Numbers.Add(new Number(2));
        Numbers.Add(new Number(3));
    }
}
public class Number
{
    public Number()
    {
    }
    public Number(int value)
    {
        this.Value = value;
    }
    [XmlAttribute]
    public int Value;
}

If I serialize the Example object I get output that looks like this:

Code:
<Example>
    <Numbers>
        <Number Value="1" />
        <Number Value="2" />
        <Number Value="3" />
    </Numbers>
</Example>

However, my desired format is simple this:

Code:
<Example>
    <Number Value="1" />
    <Number Value="2" />
    <Number Value="3" />
</Example>

Is it possible to achieve this with XmlSerialization alone or am I going to have to parse the serialized object into the format that I need?

Any help is appreciated.


 
Nevermind, I got it working... For anybody else who may have this issue here is how I fixed it...

Code:
public class Example
{
    [COLOR=#ff0000][XmlElement(typeof(Number), ElementName="Number")][/color]
    public List<Number> Numbers;

    //Populates Numbers with example data
    private PopulateList()
    {
        Numbers = new List<Number>();
        Numbers.Add(new Number(1));
        Numbers.Add(new Number(2));
        Numbers.Add(new Number(3));
    }
}
public class Number
{
    public Number()
    {
    }
    public Number(int value)
    {
        this.Value = value;
    }
    [XmlAttribute]
    public int Value;
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top