zoukankan      html  css  js  c++  java
  • 使用Linq to Xml 读取配置文件

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

    这里我们通过一个读取配置文件中某个代理中的可能url列表,先看一下Linq代理,然后再分析一下:
    string filePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\Proxy.config");
    XDocument doc 
    = XDocument.Load(filePath);

    var foundUrls 
    = from p in doc.Descendants("proxy")
                    
    where p.Attribute("proxyID").Value == "1e7c7999-274b-40b7-a4e6-d15c1c010bc6"
                    select 
    new
                    
    {
                        Urls 
    = p.Element("urls").Descendants("url").Select(u => u.Value).ToArray()
                    }
    ;
    foreach (var url in foundUrls.Single().Urls)
    {
        Response.Output.Write(url 
    + "<br/>");
    }
    其中,
    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 学习
  • 相关阅读:
    Codeforces 1265A Beautiful String
    1039 Course List for Student (25)
    1038 Recover the Smallest Number (30)
    1037 Magic Coupon (25)
    1024 Palindromic Number (25)
    1051 Pop Sequence (25)
    1019 General Palindromic Number (20)
    1031 Hello World for U (20)
    1012 The Best Rank (25)
    1011 World Cup Betting (20)
  • 原文地址:https://www.cnblogs.com/chenjunbiao/p/1760213.html
Copyright © 2011-2022 走看看