Trustos
Trustos

Reputation: 41

linq to xml getting value of an attribute out of web.config

Hello I got the following problem. I want to get the value of the baseLocation(D:\NewSites\TEST) out of the following code using linq. I tried a few things but it doesn`t seem to work. Any ideas how this would be done? Thanks in advance. Trustos

I started with something like this but this returned null

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

Here is my 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="[email protected]" />
        <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>

Upvotes: 1

Views: 1397

Answers (3)

Denys Wessels
Denys Wessels

Reputation: 17039

How about this:

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

Upvotes: 0

A J
A J

Reputation: 2140

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);

Let me know if you need further assistance, or if it helped please mark.

Upvotes: 1

Lotok
Lotok

Reputation: 4607

To use LINQ and C# to pull an attribute, use something like this

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

Upvotes: 3

Related Questions