如何从Web.config XML文件获取属性值

问题描述:

我有一个web.config文件,我想检索特定键名的连接字符串值。如何从Web.config XML文件获取属性值

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

我知道我可以通过配置管理器获取连接字符串,但我想通过XML阅读器来获取。目前我正在使用

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

我得到了两个连接字符串。但我想获得特定的“abc”连接字符串。你能帮我解决吗?

+0

只是好奇,为什么你需要使用LINQ到XML,同时ConfigurationManager中只是支持? – 2013-03-08 06:45:27

+0

实际上我想从web.config中获取连接字符串,它不在项目中 – Moiz 2013-03-08 06:47:15

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

。对象引用未设置为对象实例 – Moiz 2013-03-08 06:49:34

+0

检查我的更新 – gregjer 2013-03-08 06:55:08

+0

是gregjer这工作正常。 :-) 谢谢 – Moiz 2013-03-08 06:56:57

试试这个

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

没有,这是行不通的。 – Moiz 2013-03-08 06:44:29

+0

错误是什么?你用这个得到了什么? – 2013-03-08 06:44:53

+0

首先从哪里来这个c.name会来?因为它不会知道接收错误的属性 – Moiz 2013-03-08 06:46:34

的替代(用少量流利语法)

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