I was working on serializing list of object to xml. I got great help fron this link
After some customization I got this code
private void button1_Click(object sender, EventArgs e)
{
PersonalList personen = new PersonalList();
// normal person
Person normPerson = new Person();
normPerson.Location = "Pune";
normPerson.ChangeFrequency = "weekly";
normPerson.LastModifiedDate = "2014-07-12";
personen.AddPerson(normPerson);
Type[] personTypes = { typeof(Person)};
XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes);
FileStream fs = new FileStream("myxml.xml", FileMode.Create);
serializer.Serialize(fs, personen);
fs.Close();
personen = null;
// Deserialize
}
}
[XmlRoot("urlset")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
[XmlArray("url")]
[XmlArrayItem("url")]
public List<Person> Persons = new List<Person>();
public void AddPerson(Person person)
{
Persons.Add(person);
}
}
[XmlType("Person")] // define Type
public class Person
{
[XmlElement("loc")]
public string Location { get; set; }
[XmlElement("changefreq")]
public string ChangeFrequency { get; set; }
[XmlElement("lastmod")]
public string LastModifiedDate { get; set; }
}
This is producing result as
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<url>
<url>
<loc>Pune</loc>
<changefreq>weekly</changefreq>
<lastmod>2014-07-12</lastmod>
</url>
</url>
</urlset>
but result I want is
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<url>
<loc>Pune</loc>
<changefreq>weekly</changefreq>
<lastmod>2014-07-12</lastmod>
</url>
</urlset>
I dont want that extra element of ArrayList.
Also I need to have this at root element i.e my defined namespaces for root element.
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
Any Help?