0

我试图弄清楚如何使用 linq to 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());
    }
}

选择语句是否需要命名空间?

4

2 回答 2

2

我已将您的封闭标签更改</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
于 2013-03-27T16:18:56.287 回答
1

假设您已根据我的评论更正了您的 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);

这会给你:

WindowsServer LinuxServer

于 2013-03-27T16:35:34.403 回答