Hi
I'm trying to figure out serialization of .net arrays to XML. Here's a piece of code that I've come up with:
public class Program
{
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public uint Age { get; set; }
}
static void Main ()
{
Person[] p =
{
new Person{Age = 20, Firstname = "Michael", Lastname = "Jackson"},
new Person{Age = 21, Firstname = "Bill", Lastname = "Gates"},
new Person{Age = 22, Firstname = "Steve", Lastname = "Jobs"}
};
SerializeObject<Person[]>(p);
}
static void SerializeObject<T>(T obj) where T : class
{
string fileName = Guid.NewGuid().ToString().Replace("-", "") + ".xml";
using (FileStream fs = File.Create(fileName))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(fs, obj, ns);
}
}
}
Here's an XML content that this example writes down to the XML file:
<ArrayOfPerson>
<Person>
<Firstname>Michael</Firstname>
<Lastname>Jackson</Lastname>
<Age>20</Age>
</Person>
<Person>
<Firstname>Bill</Firstname>
<Lastname>Gates</Lastname>
<Age>21</Age>
</Person>
<Person>
<Firstname>Steve</Firstname>
<Lastname>Jobs</Lastname>
<Age>22</Age>
</Person>
</ArrayOfPerson>
But this is not really what I want. I would like it to look like this:
<Persons>
<Person>
<Firstname>Michael</Firstname>
<Lastname>Jackson</Lastname>
<Age>20</Age>
</Person>
<Person>
<Firstname>Bill</Firstname>
<Lastname>Gates</Lastname>
<Age>21</Age>
</Person>
<Person>
<Firstname>Steve</Firstname>
<Lastname>Jobs</Lastname>
<Age>22</Age>
</Person>
</Persons>
How could I get it working this way? Thanks in advance!