[英]Linq XML complex select (3 levels)
我需要從ServerConfig
的MAINDB
config部分獲取確切的參數ConnectionString
。
<?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() + " - ");
}
從所有部分中選擇所有參數。
如何編寫此查詢?
在這種情況下,使用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();
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.