Generate XML-file from your internal data

Generate XML-file from your internal data

Are you a .Net programmer and ever wanted to write your internal data to an XML-file without wanting to do the writing yourself? Well here’s some example code which can be useful for you.

First some classes representing the internal data.

[csharp]
using System.Collections.ObjectModel;

namespace XmlSerializer
{
public class DataContainer
{
public JustSomeData Data1;
public Collection Data2;
}
}
[/csharp]
[csharp]
namespace XmlSerializer
{
public class SomeMoreData
{
public long Id;
public string Name;
public int Age;
}
}
[/csharp]

The internal data will be written to a XML-file using the XmlSerializer. The following code shows a method which will initialize the internal data and will write this data to a XML-file.

[csharp highlight=”41,42-51″]
private void ShowXmlSerialization()
{
#region Init

// Main data
var dataContainer = new DataContainer();
dataContainer.Data2 = new Collection<SomeMoreData>();

#endregion Init

#region Generate some data

// Just some data
var justSomeData = new JustSomeData()
{
Id = 1,
Code = "Demo",
Description = "Just some demo data"
};

// Add it to the main data
dataContainer.Data1 = justSomeData;

// Some more data
dataContainer.Data2.Clear();
for (int i = 1; i <= 5; i++)
{
var someMoreData = new SomeMoreData();

someMoreData.Id = i;
someMoreData.Name = string.Format("Name {0}", i);
someMoreData.Age = i * 3 + i * 10;

dataContainer.Data2.Add(someMoreData);
}

#endregion Generate some data

#region Serialize

// Serialize the data
var serializer = new System.Xml.Serialization.XmlSerializer(dataContainer.GetType());

#endregion Serialize

#region Write to file

// Write it to file
var filename = "JustSomeData.xml";
Stream writer = new FileStream(filename, FileMode.Create);
serializer.Serialize(writer, dataContainer);

#endregion Write to file
}
[/csharp]

The generated XML-file will look like:

[xml]
<?xml version="1.0"?>
<DataContainer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data1>
<Id>1</Id>
<Code>Demo</Code>
<Description>Just some demo data</Description>
</Data1>
<Data2>
<SomeMoreData>
<Id>1</Id>
<Name>Name 1</Name>
<Age>13</Age>
</SomeMoreData>
<SomeMoreData>
<Id>2</Id>
<Name>Name 2</Name>
<Age>26</Age>
</SomeMoreData>
<SomeMoreData>
<Id>3</Id>
<Name>Name 3</Name>
<Age>39</Age>
</SomeMoreData>
<SomeMoreData>
<Id>4</Id>
<Name>Name 4</Name>
<Age>52</Age>
</SomeMoreData>
<SomeMoreData>
<Id>5</Id>
<Name>Name 5</Name>
<Age>65</Age>
</SomeMoreData>
</Data2>
</DataContainer>
[/xml]

Leave a Reply

Your email address will not be published. Required fields are marked *