Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize multiple objects

My serialization code is like this..

public class slab
{
    public int lowerlimit {get; set;}
    public int upperlimit { get; set; }
    public int percentage { get; set; }

}

public class Details
{
    static void Main(string[] args)
    {
        slab s= new slab();
        s.lowerlimit = 0;
        s.upperlimit = 200000;
        s.percentage = 0;
        XmlSerializer serializer = new XmlSerializer(s.GetType());
        StreamWriter writer = new StreamWriter(@"filepath");
        serializer.Serialize(writer.BaseStream, s);
    }
}

it's working fine and I am getting output file as:

<?xml version="1.0"?>
<slab xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <lowerlimit>0</lowerlimit>
    <upperlimit>200000</upperlimit>
    <percentage>0</percentage>
</slab>

But how can I serialize more than one objects? I would like to get an output file as

<slabs>
    <slab>
        <lowerlimit>0</lowerlimit>
        <upperlimit>200000</upperlimit>
        <percentage>0</percentage>
    </slab>
    <slab>
        <lowerlimit>200000</lowerlimit>
        <upperlimit>500000</upperlimit>
        <percentage>10</percentage>
    </slab>
    <slab>
        <lowerlimit>500000</lowerlimit>
        <upperlimit>1000000</upperlimit>
        <percentage>20</percentage>
    </slab>
    <slab>
        <lowerlimit>1000000</lowerlimit>
        <upperlimit>0</upperlimit>
        <percentage>30</percentage>
    </slab>
</slabs>
like image 662
Ranadheer Reddy Avatar asked Mar 06 '13 12:03

Ranadheer Reddy


1 Answers

Actually the desired output format is not valid XML, as an XML file always requires a single root element. You could put your slabs into a list (List<Slab> slabs = new List<Slab>();) and serialize that, but you'll probably get output like that:

<slabs>
    <slab>
    <lowerlimit>0</lowerlimit>
    <upperlimit>200000</upperlimit>
    <percentage>0</percentage>
    </slab>

    <slab>
    <lowerlimit>200000</lowerlimit>
    <upperlimit>500000</upperlimit>
    <percentage>10</percentage>
    </slab>

    <slab>
    <lowerlimit>500000</lowerlimit>
    <upperlimit>1000000</upperlimit>
    <percentage>20</percentage>
    </slab>

    <slab>
    <lowerlimit>1000000</lowerlimit>
    <upperlimit>0</upperlimit>
    <percentage>30</percentage>
    </slab>
</slabs>

EDIT
Another way of serializing could be this, telling the serializer more about the root element:

List<Slab> slabs = new List<Slab>();
slabs.Add(...);

XmlSerializer serializer = new XmlSerializer(slabs.GetType(), new XmlRootAttribute("slabs"));
StreamWriter writer = new StreamWriter(@"filepath");
serializer.Serialize(writer.BaseStream, slabs);
like image 51
Thorsten Dittmar Avatar answered Oct 20 '22 15:10

Thorsten Dittmar