使用Linq To XML从applicationHost.config文件中检索数据

时间:2016-07-13 15:44:56

标签: iis linq-to-xml

我正在努力获得' dontLog'的价值。 applicationHost.config文件中的以下属性:

import itertools

a = [1,1,1,0,0,1,0,1,1,0,1,1,1]

n=0
for x in itertools.groupby(a):
    c = 1
    for y in x[1]:
        c+=1
    if c==3:
        n+=1

我能够阅读所有地点'节点,但LinQ到XML可能非常混乱。 这是我的代码:

<location path="Default Web Site">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
            </authentication>
        </security>
        <httpLogging dontLog="false" />
    </system.webServer>
</location>

谢谢 最大

2 个答案:

答案 0 :(得分:1)

在VB .Net中,它将是

    Dim location As XElement
    'example given
    location = <location path="Default Web Site">
                   <system.webServer>
                       <security>
                           <authentication>
                               <windowsAuthentication enabled="true"/>
                           </authentication>
                       </security>
                       <httpLogging dontLog="false"/>
                   </system.webServer>
               </location>

    Dim dontLogValue As String = location.<system.webServer>.<httpLogging>.@dontLog

答案 1 :(得分:1)

你的问题没有说明程序运行时会发生什么(除了它不起作用),但很可能(基于你的代码玩)你没有得到任何回报,这是因为XML的结构以及.slice(-8)的工作原理。 .Elements()返回“返回此元素或文档的子元素的过滤集合”。

.Elements()中唯一的子元素是<location> - 它永远不会落到<system.webServer><httpLogging>的孩子。

与大多数事情一样,有多种方法可以完成您要做的事情。这是一个。

<system.webServer>

注意上面代码中的一些内容。首先,呼叫if (location.Name == "Default Web Site") { string dontLog = (string)e.Descendants("httpLogging").Attributes("dontLog").FirstOrDefault(); } 。与.Descendants("httpLogging")不同,.Elements()将返回当前元素的所有后代节点,并通过传入“httpLogging”,它将返回具有该名称的所有后代节点。

其次,如果属性不存在,显式转换.Descendants()将返回null(否则它将返回属性的字符串值)。

最后,根据示例结构,每组(string)只有一个<httpLogging>元素,因此调用<location>将返回第一个匹配项或默认值(null对于参考类型)如果没有。