繁体   English   中英

使用linq查询xmlnode

[英]query xmlnode using linq

我有以下文件:

<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>

我想找出以下信息:便宜和昂贵的总项目,所有类别的列表(如烹饪,园艺,装饰......),已分类的类别列表,只选择“昂贵”的产品

如何使用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());

好吧,我个人觉得使用XmlDocument更容易:

    XmlDocument root = new XmlDocument();
    root.LoadXml(xml); // or .Load(path);

    var categories = root.SelectNodes(
        "/root/Product/Product/Product/@category")
        .Cast<XmlNode>().Select(cat => cat.InnerText).Distinct();
    var sortedCategories = categories.OrderBy(cat => cat);
    foreach (var category in sortedCategories)
    {
        Console.WriteLine(category);
    }

    var totalItems = root.SelectNodes(
         "/root/Products/Product/Product").Count;
    Console.WriteLine(totalItems);

    foreach (XmlElement prod in root.SelectNodes(
        "/root/Product/Product[@desc='Costly']/Product"))
    {
        Console.WriteLine(prod.GetAttribute("desc"));
    }

暂无
暂无

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

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