繁体   English   中英

Linq to xml选择语句

[英]Linq to xml Select statement

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

select语句是否需要名称空间?

我已将您将标签</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);

这会给你:

WindowsServer LinuxServer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM