如何使用 Linq 打开 Open XML

哈维尔·帕拉

嗨,我想通过过滤器从我的 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>

杰勒鲁

您面临的问题(最有可能)是“Connections”是“Connection”元素的集合,当您尝试按属性过滤它们时,您将只检查第一个元素。您需要先使用 SelectMany 将集合展平:

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

然后在您的结果中,您将拥有一个“Connection”类型的 XElements 集合:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章