2017-04-06 62 views
0

您好,我想從我的xml 的屬性環境中獲取過濾器的連接,但即時通訊可以幫助您解決一些錯誤。如何使用Linq打開Open XML

這裏是我的代碼:

XElement xelement = XElement.Load(xml); 
 
var Connections = from conn in xelement.Elements("Conections") 
 
        where (String)conn.Element("Conection").Attribute("Enviroment") == "Test" 
 
        select conn; 
 

 
foreach (XElement conection in Connections) 
 
{ 
 
    MessageBox.Show(conection.Element("Conection").Value); 
 
}

,這裏是我的XML

<?xml version="1.0" encoding="utf-8"?> 
 
<Config> 
 
    <General> 
 
    <FormaInicial></FormaInicial> 
 
    <DiasRecordatorioBuro></DiasRecordatorioBuro> 
 
    <EnviarSMSDomiciliacion>rue</EnviarSMSDomiciliacion> 
 
    <SimularDeathLock></SimularDeathLock> 
 
    <IsProductionEnviroment></IsProductionEnviroment> 
 
    <WaitingTimeBetweenExecutions></WaitingTimeBetweenExecutions> 
 
    <NumberTriesBeforeRestartService></NumberTriesBeforeRestartService> 
 
    </General> 
 
    <Conections> 
 
    <Conection Enviroment="Production"> 
 
     <Servidor></Servidor> 
 
     <BaseDatos>==</BaseDatos> 
 
     <Usuario></Usuario> 
 
     <Password></Password> 
 
    </Conection> 
 
    <Conection Enviroment="Test"> 
 
     <Servidor></Servidor> 
 
     <BaseDatos></BaseDatos> 
 
     <Usuario></Usuario> 
 
     <Password></Password> 
 
    </Conection> 
 
    </Conections> 
 
</Config>

+0

請而非HTML/JavaScript的/ CSS有問題的代碼使用'{}',你在拼寫問題時也拼錯了'how' – Jpsh

+1

究竟是什麼錯誤? – har07

回答

0

你所面臨的問題(最有可能)是「連接」是「連接」元素的集合,並且當您嘗試按屬性過濾它們時 - 只會檢查第一個元素。您需要首先拼合的收集,使用的SelectMany:

var connections = xelement.Elements("Conections") 
      .SelectMany(c => c.Elements("Conection")) 
      .Where(c => c.Attribute("Enviroment").Value == "Test"); 

然後在你的結果,你將有類型的「連接」的XElements集合:

foreach (var conection in connections) 
{ 
    Console.WriteLine(conection); //a full element with Servidor, BaseDatos, Usuario and Password 
    Console.WriteLine(conection.Element("Servidor").Value);  
} 
+0

謝謝你的完美。你真的很有幫助 –