简体   繁体   English

LINQ 到 XML 复杂查询过滤

[英]LINQ to XML complex query filtering

I have this code based on Microsoft docs.我有这个基于微软文档的代码。

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-write-queries-with-complex-filtering https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-write-queries-with-complex-filtering

string xml =
  "<products>" +
    "<product name=\"p1\">" +
      "<market name=\"m1\">" +
        "<areacode>12345</areacode>" +
        "<areacode>12346</areacode>" +
      "</market>" +
      "<market name=\"m2\">" +
        "<areacode>12345</areacode>" +
        "<areacode>13346</areacode>" +
      "</market>" +
      "<market name=\"m3\">" +
        "<areacode>12346</areacode>" +
        "<areacode>13346</areacode>" +
      "</market>" +
    "</product>" +
    "<product name=\"p2\">" +
      "<market name=\"m1\">" +
        "<areacode>12340</areacode>" +
        "<areacode>12346</areacode>" +
      "</market>" +
      "<market name=\"m2\">" +
        "<areacode>12340</areacode>" +
        "<areacode>13346</areacode>" +
      "</market>" +
      "<market name=\"m3\">" +
        "<areacode>12346</areacode>" +
        "<areacode>13346</areacode>" +
      "</market>" +
    "</product>" +
  "</products>";
XElement prods = XElement.Parse(xml);
IEnumerable<XElement> els =
  from e1 in prods.Elements("product")
  where
    (string)e1.Attribute("name") == "p1" &&
    (
      from e2 in e1.Elements("market")
      where
        (
          from e3 in e2.Elements("areacode")
          where e3.Value == "12345"
          select e3
        ).Any()
      select e2
    ).Any()
  select e1;
foreach (XElement el in els)
  Console.WriteLine(el);

The output is output 是

<product name="p1">
  <market name="m1">
    <areacode>12345</areacode>
    <areacode>12346</areacode>
  </market>
  <market name="m2">
    <areacode>12345</areacode>
    <areacode>13346</areacode>
  </market>
  <market name="m3">
    <areacode>12346</areacode>
    <areacode>13346</areacode>
  </market>
</product>

How can I exclude markets that do not have the specified area code from the output?如何从 output 中排除没有指定区号的市场? Product name, market name and area codes are all required for the rest of the code if it matches the condition.代码的rest如果符合条件,则需要产品名称、市场名称和地区代码。

There's no easy way to create a new tree that has just what you want, since you can't filter children directly.没有简单的方法来创建一个拥有你想要的新树,因为你不能直接过滤孩子。 However, you can modify your tree:但是,您可以修改树:

prods.Descendants("market").Where(m => m.Descendants("areacode").All(a => a.Value != "13346")).Remove();
prods.Descendants("product").Where(p => !p.Descendants("market").Any()).Remove();

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

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