Not KML, but here is an example using System.Xml.Serialization
Given these two classes (with attributes) and initialization:
[XmlRoot("BookList")]
public class BookList
{
[XmlElement("BookData")]
public List<Book> Books = new List<Book>();
}
public class Book
{
[XmlElement("Title")]
public string Title { get; set; }
[XmlAttribute("isbn")]
public string ISBN { get; set; }
}
var bookList = new BookList
{
Books = { new Book { Title = "Once in a lifetime", ISBN = "135468" } }
};
You can serialize in xml as follows:
var serializer = new XmlSerializer(typeof(BookList));
using (var writer = new StreamWriter("YourFileNameHere"))
{
serializer.Serialize(writer, bookList);
}
Equivalent Linq to Xml will look something like this (not verified)
XElement bookXML =
new XElement("BookList",
from book in bookList.Books
select new XElement("BookData",
new XElement("Title", book.Title),
new XAttribute("isbn", book.ISBN)
)
);
Conclusion, both cleaner than using XmlDocument, XmlSerializer is shorter, Linq to XML gives you more flexibility (XmlSerializer is pretty "tough" in terms of how different your class structure is for your xml structure).
source
share