linq to xml从web.config中获取属性的值

时间:2013-04-10 08:42:25

标签: c# asp.net xml linq

您好我遇到了以下问题。我想使用linq从以下代码中获取 baseLocation(D:\ NewSites \ TEST )的值。 我尝试了一些东西,但它似乎没有用。 任何想法如何做到这一点? 提前致谢。 Trustos

我从这样的事情开始,但这返回了null

XDocument document = XDocument.Load("C:\\web.config");
var dataList = from item in document.Descendants("configuration") select item;

这是我的XML

<?xml version="1.0"?>
<configuration>
    <configSections>
    </configSections>
    <log4net>
    </log4net>
    <web>
        <website runtimeMode="Development" siteName="TEST" baseLocation="D:\NewSites\TEST"      sitePath="D:\NewSites\TEST\WebApps\Website" siteUri="http://test.co.uk" s    iteEmail="test@gmail.com" />
        <cms defaultTemplate="TEST\Content.aspx" templatesUrl="/Manager/Templates/">
        <publishingLocations>
            <publishingLocation name="TEST" uri="http://test.co.uk" path="WebApps\Website" />
        </publishingLocations>
        <redirectables />
        <searchEngineSiteMapNotifications />
        <siteMapXmlUrls />
        <pingServices />
        <reservedTemplates />
        <templateFilters />
        </cms>
    </web>
    <location path="Manager">
    </location>
    <connectionStrings>
    </connectionStrings>
    <system.web>
    </system.web>
</configuration>

3 个答案:

答案 0 :(得分:2)

要使用LINQ和C#来提取属性,请使用类似

的内容
XDocument document = Xdocument.Load("~/web.config");
var location = document.Descendants().Single(i=>i.Attribute("baseLocation") !=null)
               .Attribute("baseLocation").Value;

答案 1 :(得分:1)

This will do the task:

XmlDocument xml = new XmlDocument();
xml.Load(@"location of xml/config");//  xml.Load(@""~/web.config");
XmlNode node = xml.DocumentElement.SelectSingleNode("//website");
Response.Write(node.Attributes["baseLocation"].Value);

如果您需要进一步的帮助,或者如果它有帮助,请告诉我。请标记。

答案 2 :(得分:0)

这个怎么样:

string baseLocation = document.Descendants("website").First().Attribute("baseLocation").Value;