c# - 使用 linq 查询 xmlnode

标签 c# linq linq-to-xml

我有以下文件:

<root>
  <Product desc="Household">
    <Product1 desc="Cheap">
        <Producta desc="Cheap Item 1" category="Cooking" />
        <Productb desc="Cheap Item 2" category="Gardening" />
    </Product1>
    <Product2 desc="Costly">
        <Producta desc="Costly Item 1" category="Decoration"/>
        <Productb desc="Costly Item 2" category="Furnishing" />
        <Productc desc="Costly Item 3" category="Pool" />
    </Product2>
  </Product>
</root>

我想了解以下信息:便宜和昂贵的商品总数, 所有类别的列表(如 cooking 、园艺、装饰......),排序类别的列表并仅选择“昂贵”的产品

我如何使用 LINQ。 到目前为止,我一直这样做:

 XElement xe = XElement.Load(Server.MapPath("~/product.xml"));
 ????

最佳答案

您的 XML 结构很不幸,因为它对层次结构的三个级别使用 Product 元素。你还有其他类似于“家用”的元素吗?

假设我们只想要家庭用品,您可以使用:

计算便宜/昂贵的元素

xe.Element("Product") // Select the Product desc="household" element
  .Elements() // Select the elements below it
  .Select(element => new { Name=(string) element.Attribute("desc"),
                           Count=element.Elements().Count() });

列出所有类别

xe.Descendants() // Select all descendant elements
  .Attributes() // All attributes from all elements
  // Limit it to "category" elements
  .Where(attr => attr.Name == "category")
  // Select the value
  .Select(attr => attr.Value)
  // Remove duplicates
  .Distinct();

要对此进行排序,只需在末尾使用 .OrderBy(x => x)

选择“昂贵”的产品

xe.Descendants() // Select all elements
  // Only consider those with a "Costly" description
  .Where(element => (string) element.Attribute("desc") == "Costly")
  // Select the subelements of that element, and flatten the result
  .SelectMany(element => element.Elements());

关于c# - 使用 linq 查询 xmlnode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576678/

相关文章:

c# - 在 Unity3d 中运行 SQL 的协程

c# - 在 WPF/C# 中生成复杂内容并将其传递给 GUI 线程

c# - 重复 LINQ 查询

c# - 我可以 LINQ 一个 JSON 吗?

c# - FileUpload 加载 .XML

c# - LINQ自引用表过滤关系

c# - 如何在 windows 8 Apps 中获取 webview 的当前 URL | C#、XMAL

c# - 基于另一个列表过滤列表 - LINQ

c# - 使用 LINQ to XML 使用文本和元素节点展平 xml

c# - 检查 LINQ to XML 中的单独节点