frcnav10
frcnav10

Reputation: 13

How can I create multiple XML files in C# when a stored procedure that is called returns a large number of rows?

Currently, I am developing a console application which does the following:

  1. Executes a SQL Server stored procedure to get data like a mobile phone number, etc..

  2. Creates one or multiple XML files with the following catch - there can only be a maximum of 100 elements per file.

So imagine the below:

I have a Car class, and the Car class as the following properties:

Make, Year, Model, Color, Number Of Axles

Then I have a

List<Car> myCars = new List<Car>(); 

The Car class is now populated by the stored procedure, and in the console application code I use the default constructor, populate the list, etc...

I find that myCars.Count = 200. I want to have two XML files that would look like this:

<!--First xml file-->
<myCars>
     <!-- first set of 100 cars-->
</myCars>

Then the second file

<!-- Second xml file-->
<myCars>
    <!-- second set of 100 cars from the myCars list -->
</myCars>

I am using the XDocument and the Linq to XML technology. Please help!

Upvotes: 0

Views: 784

Answers (3)

Sir Rufo
Sir Rufo

Reputation: 19106

You can create partitions from a collection with

int partitionSize = 100;
var partitions = collection
    .Select( (e,i) => new { Partition = i / partitionSize, Element = e } )
    .ToLookup( e => e.Partition, e => e.Element );

and then serialize each partition into a file

foreach ( var partition in partitions )
{
    var filename = string.Format( "file_{0}.xml", partition.Key ));
    // write the partition to the file
}

Upvotes: 1

loopedcode
loopedcode

Reputation: 4893

Just use XmlSerializer to create xml of your cars. Select in batch of 100 to create new xml file for that set.

Something like this:

 XmlSerializer ser = new XmlSerializer(typeof(List<Car>));
 int carsPerFile = 100;
 int fileIndex = 1;
 for(int i=0; i<myCars.Count; )
 {
    var cars = myCars.Skip(i).Take(carsPerFile);
    using (var text = XmlWriter.Create(string.Contact("myCars_",fileIndex++,".xml"))
    {
        ser.Serialize(text, cars.ToList());
    }
    i += carsPerFile;
 }

Upvotes: 3

aaylmao
aaylmao

Reputation: 105

List<Car> firstHundred = myCars.Take(100); // first 100
List<Car> secondHundred = myCars.Skip(100).Take(100) // 100-200

Then serialize these two lists to a different xml file.

Upvotes: 0

Related Questions