不是 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);
}
与 XML 等效的 Linq 看起来像这样(未经测试)
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 为您提供更大的灵活性(XmlSerializer 在您的类结构与 xml 结构的不同方面非常“刚性”)。