Linq to Xml 大大简化了对xml文件的操作,匿名对象、Lambda表达式、Linq等C#3.0的新特性改变了我们不少的编程习惯,通过Linq我们可以有一种统一的操作集合和对象的方法,下面我们写一个例子来感受一下Linq to Xml的魅力。
首先这里有一个xml配置文件,用来配置一个Web代理,根据调用传入的ProxyID来判断调用是否有权限访问对应的服务(asmx),配置文件如下:
使用Linq to Xml 读取配置文件<?xml version="1.0" encoding="utf-8" ?>
使用Linq to Xml 读取配置文件
<proxySet>
使用Linq to Xml 读取配置文件    
<proxy proxyID="1e7c7999-274b-40b7-a4e6-d15c1c010bc6" description="">
使用Linq to Xml 读取配置文件        
<urls>
使用Linq to Xml 读取配置文件            
<url>http://www.face512.com/UpdatingSource1.asmx</url>
使用Linq to Xml 读取配置文件            
<url>http://www.face512.com/UpdatingSource2.asmx</url>
使用Linq to Xml 读取配置文件            
<url>http://www.face512.com/UpdatingSource3.asmx</url>
使用Linq to Xml 读取配置文件        
</urls>
使用Linq to Xml 读取配置文件    
</proxy>
使用Linq to Xml 读取配置文件    
<proxy proxyID="5dfbe758-3ac7-4e8c-bd1e-6d0cc2e34d99" description="">
使用Linq to Xml 读取配置文件        
<urls>
使用Linq to Xml 读取配置文件            
<url>http://www.face512.com/test01.asmx</url>
使用Linq to Xml 读取配置文件        
</urls>
使用Linq to Xml 读取配置文件    
</proxy>
使用Linq to Xml 读取配置文件    
<proxy proxyID="8f097253-e8dc-489f-86df-19b08c2d7ce2" description="">
使用Linq to Xml 读取配置文件        
<urls>
使用Linq to Xml 读取配置文件            
<url>http://www.face512.com/test02.asmx</url>
使用Linq to Xml 读取配置文件        
</urls>
使用Linq to Xml 读取配置文件    
</proxy>
使用Linq to Xml 读取配置文件
</proxySet>

这里我们通过一个读取配置文件中某个代理中的可能url列表,先看一下Linq代理,然后再分析一下:
使用Linq to Xml 读取配置文件string filePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\Proxy.config");
使用Linq to Xml 读取配置文件XDocument doc 
= XDocument.Load(filePath);
使用Linq to Xml 读取配置文件
使用Linq to Xml 读取配置文件var foundUrls 
= from p in doc.Descendants("proxy")
使用Linq to Xml 读取配置文件                
where p.Attribute("proxyID").Value == "1e7c7999-274b-40b7-a4e6-d15c1c010bc6"
使用Linq to Xml 读取配置文件                select 
new
}
其中,
Descendants 可遍历某节点或文档下的所有子节点
Elements 则是遍历当前节点或文档下一级的子节点
这里通过Descendants遍历所有的proxy节点,并且只处理proxy的proxyID属性为指定值的节点;
通过p.Element("urls")获取urls获了节点;
p.Element("urls").Descendants("url") 遍历其中的url节点集
.Select(u => u.Value) 只取其中的节点值,最后通过ToArray()转换数组赋值组Urls变量

因为这里我们知道在proxy节点中urls只有一个这样的节点,所以这里就可以不需要使用foreach遍历foundUrls,而是通过foundUrls.Single()就可以获取其唯一的对象,最后通过遍历Urls数组就可以得出此代理中所有的允许访问的URL了
http://www.face512.com/UpdatingSource1.asmx
http://www.face512.com/UpdatingSource2.asmx
http://www.face512.com/UpdatingSource3.asmx


参考:Linq To XML 学习

相关文章: