这一次,我们来看一下如果使用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格式
LinQ in Action 笔记二:Hello LINQ to XML<books>
LinQ in Action 笔记二:Hello LINQ to XML    
<book title="Windows Forms in Action">
LinQ in Action 笔记二:Hello LINQ to XML        
<publisher>Manning</publisher>
LinQ in Action 笔记二:Hello LINQ to XML    
</book>
LinQ in Action 笔记二:Hello LINQ to XML    
<book title="RSS and Atom in Action">
LinQ in Action 笔记二:Hello LINQ to XML        
<publisher>Manning</publisher>
LinQ in Action 笔记二:Hello LINQ to XML    
</book>
LinQ in Action 笔记二:Hello LINQ to XML
</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的结构层次

相关文章:

  • 2021-05-27
  • 2022-12-23
  • 2021-06-15
  • 2022-01-14
  • 2022-12-23
  • 2021-09-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-05
  • 2021-05-20
  • 2022-12-23
  • 2021-09-09
  • 2021-06-20
相关资源
相似解决方案