Linq to xml Select statement

本文关键字:statement Select xml to Linq | 更新日期: 2023-09-27 18:06:22

我想弄清楚如何使用linq到xml做一个选择语句。如果DeploymentType等于一个特定的值(Enterprise9999),我想返回ServerTypes。

XML:

<Deployments>
  <Deployment>
    <DeploymentType>Enterprise9999</EnterpriseDeploymentType>
    <Servers>
      <DeploymentServer>
        <ServerType>WindowsServer</ServerType>
      </DeploymentServer>
      <DeploymentServer>
        <ServerType>LinuxServer</ServerType>
      </DeploymentServer>
    </Servers>
  </Deployment>
  <Deployment></Deployment>
  <Deployment></Deployment>
</Deployments>

这是到目前为止我在代码中的内容。我确定我用错了方法:

XDocument xmlDoc = XDocument.Load(@xmlFile);
IEnumerable<XElement> xlDeployments = from depRows in xmlDoc.Descendants("Deployments")
                                           select depRows;
var deploy = xlDeployments.Descendants("Deployment");
foreach (var dep in deploy)
{
    if (dep.Element("DeploymentType").ToString() == "Enterprise9999")
    {
        MessageBox.Show(dep.Elements("ServerType").ToString());
    }
}

选择语句需要命名空间吗?

Linq to xml Select statement

我把你的标签</EnterpriseDeploymentType>改成了</DeploymentType>

XDocument xmlDoc = XDocument.Load(@xmlFile);
var deployments = xmlDoc.Descendants("Deployment")
                       .Where(dep => dep.Element("DeploymentType") != null 
                                  && dep.Element("DeploymentType").Value == "Enterprise9999");
var servers = deployments.Descendants("ServerType")
                         .Select(node => node.Value);
Console.WriteLine(string.Join(Environment.NewLine, servers));

打印:

WindowsServer
LinuxServer

假设您已经按照我的评论更正了您的XML,您可以使用以下单个查询:-

var nodes = from n in xml.Descendants("DeploymentType")
                     .Where(x => x.Element("EnterpriseDeploymentType").Value.Equals("Enterprise9999"))
                        select n.Descendants("Servers").Descendants("ServerType").Select(s => s.Value);

这将给你:

WindowsServerLinuxServer