0

我需要ConnectionString从.MAINDBServerConfig

<?xml version="1.0" encoding="utf-8" ?>
<ServerConfig>
  <config section="MAINDB">
    <parameter type="ConnectionString">"CONNSTRING"</parameter>
    <parameter type="ConnectionString1">"CONNSTRING1"</parameter>
    <parameter type="ConnectionString2">"CONNSTRING2"</parameter>
    <parameter type="ConnectionString3">"CONNSTRING3"</parameter>
  </config>
  <config section="OTHERDB">
    <parameter type="ConnectionString">"CONNSTRING"</parameter>
    <parameter type="ConnectionString1">"CONNSTRING1"</parameter>
    <parameter type="ConnectionString2">"CONNSTRING2"</parameter>
    <parameter type="ConnectionString3">"CONNSTRING3"</parameter>
  </config>
  <config section="OTHERPARAM">
    <parameter type="OtherString">"OTHERSTRING"</parameter>
  </config>
</ServerConfig>

我用 Linq 尝试了几种方法,但都没有成功。

我的最后一次尝试:

var parameters =
    from el in xdoc.Elements(GivenSystem)
    where (from add in el.Elements("config")
          where (string)add.Attribute("section") == ConfigSection
          select add).Any()
    select el;

foreach (var t in parameters)
{
    Console.WriteLine(t.Value.ToString() + " - ");
}                

从所有部分中选择所有参数。

我该如何编写这个查询?

4

2 回答 2

1

在这里使用 xpath 的情况要干净得多。LINQ to XML 查询可能会有点冗长。

const string configSection = "MAINDB";
const string parameterType = "ConnectionString";

// using xpath //
var xpath = String.Format(
    "/ServerConfig/config[@section='{0}']/parameter[@type='{1}']",
    configSection, parameterType
);
var query1 = (string)doc.XPathSelectElement(xpath);

// using LINQ //
var query2 =
    (from config in doc.Elements("ServerConfig").Elements("config")
    where (string)config.Attribute("section") == configSection
    from parameter in config.Elements("parameter")
    where (string)parameter.Attribute("type") == parameterType
    select (string)parameter).FirstOrDefault();
于 2013-04-19T06:06:01.277 回答
0
var connectionString = (from c in xdoc.Root.Elements("config")
                        where (string) c.Attribute("section") == "MAINDB"
                        from p in c.Elements("parameter")
                        where (string) p.Attribute("type") == "ConnectionString"
                        select (string) p).FirstOrDefault();

connectionString将包含您的价值,或者将null在未找到时包含您的价值。

于 2013-04-19T06:04:27.910 回答