Reputation: 4324
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>
Upvotes: 8
Views: 19631
Reputation: 11
Use
XmlSerializer serializer = new XmlSerializer(**slabs**.GetType(), new XmlRootAttribute("slabs"));
Instead of
XmlSerializer serializer = new XmlSerializer(s.GetType(), new XmlRootAttribute("slabs"));
Upvotes: 0
Reputation: 56697
Actually the desired output format is not valid XML, as an XML file always requires a single root element. You could put your slab
s 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);
Upvotes: 9
Reputation: 7501
To encapsulate nicely, and ensure the type name, you could create a new object called slabs, that contains just a List<Slab>
. Add the slabs to this new object and serialize it.
Upvotes: 2
Reputation: 6490
You can make use of following code.
List<Slab> listSlabs = new List<Slab>();
//add Slab to listSlabs
You can serialize the list.
Upvotes: 1