Simple example for Linq To XML

The XML Source file is:

  1. <?xml version="1.0" encoding="GB2312"?>
  2. <Books>
  3.   <Book genre="Mystery" publicationdate="2001" ISBN="123456789">
  4.     <title>The Case of the Missing Cookie</title>
  5.     <author Country="America">
  6.       <Name>Cookie Monster</Name>
  7.     </author>
  8.     <Price>$9.99</Price>
  9.   </Book>
  10.   <ALFKI />
  11.   <ANATR />
  12.   <ANTON />
  13.   <AROUT />
  14.   <BERGS />
  15.   <ALFKI />
  16.   <ANATR />
  17.   <ANTON />
  18.   <AROUT />
  19.   <BERGS />
  20.   <ALFKI />
  21.   <ANATR />
  22.   <ANTON />
  23.   <AROUT />
  24.   <BERGS />
  25. </Books>

2. You must add reference for Linq To XML

  1. using System.Xml.Linq;

3. Select nodes you want, now i will select all the sub nodes which start with character "A".

  1. XDocument doc = XDocument.Load("d://ddd.xml");
  2.             // build linq query
  3.             var query = from c in doc.Elements("Books").Elements()
  4.                         where c.Name.ToString().StartsWith("A")
  5.                         select c;
  6.             // visit every element in the query
  7.             foreach (XElement a in query)
  8.             {
  9.                 Console.WriteLine(a.Name);
  10.             }
  11.             // in this sentence we can get the total count of the query
  12.             Console.WriteLine("The records count is {0}.",query.Count());

The result is as follows:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值