惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
Recent Announcements
Recent Announcements
雷峰网
雷峰网
The GitHub Blog
The GitHub Blog
罗磊的独立博客
月光博客
月光博客
J
Java Code Geeks
A
About on SuperTechFans
Microsoft Security Blog
Microsoft Security Blog
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Fortinet All Blogs
U
Unit 42
C
Check Point Blog
Martin Fowler
Martin Fowler
有赞技术团队
有赞技术团队
博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog

博客园 - 滋心

为hover事件加上延迟 面向对象的JavaScript(2)闭包 面向对象的JavaScript(1):创建简单的类 JQuery画细线表格 自定义控件验证页面所有文本框 - 滋心 - 博客园 LinQ in Action 笔记三:Hello LINQ to SQL LinQ in Action 笔记一、Hello LINQ to Objects JQuery选择器插件 Extra selectors JQuery选择器 - 滋心 - 博客园 利用Repeater控件显示主-从关系数据表 查询表结构 Sqlserver建立和另外数据库的连接 XPath实例教程十九、ancestor-or-self 轴(axis)包含上下文节点本身和该节点的祖先节点 XPath实例教程十八、descendant-or-self 轴 XPath实例教程十七、preceding轴 XPath实例教程十六、following轴 XPath实例教程十五、preceding-sibling 轴 XPath实例教程十四、following-sibling轴 XPath实例教程十三、ancestor轴
LinQ in Action 笔记二:Hello LINQ to XML
滋心 · 2008-07-05 · via 博客园 - 滋心

这一次,我们来看一下如果使用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的结构层次