不是 KML,但这里有一个使用 System.Xml.Serialization 的例子。
给定这两个类(带属性)和初始化:
[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" } }
};
你可以像这样序列化为xml:
var serializer = new XmlSerializer(typeof(BookList));
using (var writer = new StreamWriter("YourFileNameHere"))
{
serializer.Serialize(writer, bookList);
}
一个等效的 Linq to Xml 代码大概是这样的(未经测试)
XElement bookXML =
new XElement("BookList",
from book in bookList.Books
select new XElement("BookData",
new XElement("Title", book.Title),
new XAttribute("isbn", book.ISBN)
)
);
总结一下,与使用XmlDocument相比,两者都更加简洁明了,XmlSerializer更短,而Linq to XML则提供更大的灵活性(在类结构与xml结构不同的情况下,XmlSerializer相对“严格”)。