这一次,我们来看一下如果使用LinQ来查询和创建XML

我们有一个book类:
class Book
{
  
public string Title;
  
public string Publisher;
  
public int    Year;

  
public Book(string title, string publisher, int year)
  {
    Title 
= title;
    Publisher 
= publisher;
    Year 
= year;
  }
}
我们实例化一个book的集合
Book[] books = new Book[] {
  
new Book("Ajax in Action""Manning"2005),
  
new Book("Windows Forms in Action""Manning"2006),
  
new Book("RSS and Atom in Action""Manning"2006)
};

如果我们现在想将Year== 2006的集合创建成以下XML格式
<books>
    
<book title="Windows Forms in Action">
        
<publisher>Manning</publisher>
    
</book>
    
<book title="RSS and Atom in Action">
        
<publisher>Manning</publisher>
    
</book>
</books>

按照传统的方式,我们将如何实现呢?
XmlDocument doc = new XmlDocument();
XmlElement root 
= doc.CreateElement("books");
foreach (Book book in books)
{
  
if (book.Year == 2006)
  {
    XmlElement element 
= doc.CreateElement("book");
    element.SetAttribute(
"title", book.Title);

    XmlElement publisher 
= doc.CreateElement("publisher");
    publisher.InnerText 
= book.Publisher;
    element.AppendChild(publisher);

    root.AppendChild(element);
  }
}
doc.AppendChild(root);

// 显示这个XML
doc.Save(Console.Out);

如果我们采用LinQ:
XElement xml = new XElement("books",
  from book 
in books
  
where book.Year == 2006
  select 
new XElement("book",
    
new XAttribute("title", book.Title),
    
new XElement("publisher", book.Publisher)
  )
);

// 显示这个XML
Console.WriteLine(xml);
有没有发现,代码量减少了好多,而且结构更加清晰了,如果你的换行和缩进排版比较规范的话,你甚至能直观的从代码中看出XML的结构层次
posted on 2008-07-05 05:52  滋心  阅读(297)  评论(0编辑  收藏  举报