我有以下文件:
<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/