不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給你更大的靈活性(XmlSerializer在類結構與xml結構的差異方面相當「僵化」)。
問問關於linq的問題,這個答案並沒有說明如何使用XmlSerializer類。 – Benjol 2009-04-27 11:49:40