我正在将对象列表序列化为xml。我得到了很大的帮助link
经过一些自定义后,我得到了这段代码
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; }
}
这是以
生成结果<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>
但我想要的结果是
<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>
我不想要ArrayList的额外元素。
此外,我需要在root元素处拥有它,即我为root元素定义的命名空间。
<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">
任何帮助?