Moiz
Moiz

Reputation: 2439

How to fetch attribute values from Web.config XML file

I have a web.config file and i want to retrieve the connection string value of particular key name.

<connectionStrings>
        <add name="abc" connectionString="Server=(local);Initial Catalog=abc;Integrated Security=SSPI;Max Pool Size=25" providerName="System.Data.SqlClient" />
        <add name="cde" connectionString="Server=(local);Initial Catalog=cde; Integrated Security=SSPI;Max Pool Size=50" providerName="System.Data.SqlClient" />
    </connectionStrings>

I know i can fetch the connection string by configurationManager but i want to get that through XML reader. Presently i am using

XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants(connectionStrings)
select c ;

I am getting both the connection string. but i want to get specific "abc" connection string. can you please help me out.

Upvotes: 1

Views: 1592

Answers (3)

Bhushan Firake
Bhushan Firake

Reputation: 9458

Try this

XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings")
                       where c.name=="abc"               
                       select c ;

Upvotes: 0

Hexie
Hexie

Reputation: 4221

An alternative (using a little fluent syntax)

var connectionString = document.Descendants("connectionStrings")
                       .Descendants("add")
                       .First(x => x.Attribute("name").Value == "abc").Attribute("connectionString").Value;

Upvotes: 1

gregjer
gregjer

Reputation: 2843

XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings").Descendants("add")
    where c.Attribute("name").Value == "abc"                
    select c;

Upvotes: 2

Related Questions