CodexBloom - Programming Q&A Platform

LINQ to XML - how to to Filter Nested Elements Based on Attribute Values

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
linq xml c# query C#

I've been banging my head against this for hours. I'm working on a personal project and I'm working with LINQ to XML in C# to filter a collection of XML elements based on specific attribute values. I have an XML structure where I want to find all `Book` elements that belong to a certain `Category` and have a `Price` greater than a specified value. However, my current LINQ query isn't returning the expected results. Here's a simplified version of my XML: ```xml <Library> <Book Category="Fiction" Price="9.99"> <Title>The Great Gatsby</Title> <Author>F. Scott Fitzgerald</Author> </Book> <Book Category="Non-Fiction" Price="14.99"> <Title>Educated</Title> <Author>Tara Westover</Author> </Book> <Book Category="Fiction" Price="12.99"> <Title>1984</Title> <Author>George Orwell</Author> </Book> </Library> ``` And here's the LINQ query I've written: ```csharp XDocument doc = XDocument.Load("library.xml"); var filteredBooks = from book in doc.Descendants("Book") where (string)book.Attribute("Category") == "Fiction" && (decimal)book.Attribute("Price") > 10.00m select book; ``` When I execute this, it returns no results, but I expect it to return the `1984` book. I've checked the attribute names and data types, and they seem to be correct. I'm not sure if I'm missing something regarding type conversion or if there's an scenario with how I'm filtering the data. I've also tried casting the `Price` attribute directly in the query and using `decimal.TryParse` for safety, but it still yields no results. Has anyone encountered a similar scenario or can provide insight into why this might not be working as expected? This issue appeared after updating to C# LTS. Thanks for your help in advance! This is for a microservice running on Windows 11. Thanks, I really appreciate it!