如何从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”连接字符串。你能帮我解决吗?
答
XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings").Descendants("add")
where c.Attribute("name").Value == "abc"
select c;
答
试试这个
XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings")
where c.name=="abc"
select c ;
答
的替代(用少量流利语法)
var connectionString = document.Descendants("connectionStrings")
.Descendants("add")
.First(x => x.Attribute("name").Value == "abc").Attribute("connectionString").Value;
只是好奇,为什么你需要使用LINQ到XML,同时ConfigurationManager中只是支持? – 2013-03-08 06:45:27
实际上我想从web.config中获取连接字符串,它不在项目中 – Moiz 2013-03-08 06:47:15