我正在尝试弄清楚如何使用linq to xml执行select语句。如果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语句是否需要命名空间?
答案 0 :(得分: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
答案 1 :(得分: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