1

我有一个 web.config 文件,我想检索特定键名的连接字符串值。

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

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

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

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

4

3 回答 3

2
XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings").Descendants("add")
    where c.Attribute("name").Value == "abc"                
    select c;
于 2013-03-08T06:47:45.320 回答
1

另一种选择(使用一点流利的语法)

var connectionString = document.Descendants("connectionStrings")
                       .Descendants("add")
                       .First(x => x.Attribute("name").Value == "abc").Attribute("connectionString").Value;
于 2013-03-08T07:07:42.200 回答
0

试试这个

XDocument document = XDocument.Load(fullPath);
var connectionString = from c in document.Descendants("connectionStrings")
                       where c.name=="abc"               
                       select c ;
于 2013-03-08T06:41:57.043 回答