2013-04-19 3 views
0

Мне нужно получить точный параметр ConnectionString из раздела конфигурации MAINDB от ServerConfig.Linq XML complex select (3 уровня)

<?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() + " - "); 
}     

выбирает все параметры из всех разделов.

Как я могу написать этот запрос?

ответ

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, когда он не нашел.

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();