首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用linq查询xmlnode

使用linq查询xmlnode
EN

Stack Overflow用户
提问于 2009-02-23 06:20:33
回答 2查看 21.7K关注 0票数 11

我有以下文件:

代码语言:javascript
复制
<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>

我想找出这样的信息:在便宜和昂贵的项目总数,所有类别的列表(如烹饪,园艺,DEcoration...),排序的类别列表,并只选择产品是‘昂贵’

如何使用LINQ。我一直这样做到现在:

代码语言:javascript
复制
 XElement xe = XElement.Load(Server.MapPath("~/product.xml"));
 ????
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-02-23 07:27:32

您的XML结构很糟糕,因为它在层次结构的三个级别使用了Product元素。你有没有类似于“家庭”元素的其他元素?

假设我们只想要家用的,你可以使用:

每个便宜/昂贵的中的计数项目

代码语言:javascript
复制
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() });

列出所有类别

代码语言:javascript
复制
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)

精选“昂贵”产品

代码语言:javascript
复制
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());
票数 9
EN

Stack Overflow用户

发布于 2009-02-23 07:42:07

嗯,就我个人而言,我发现使用XmlDocument更容易

代码语言:javascript
复制
    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"));
    }
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/576678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档