Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 234265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T20:10:15+00:00 2026-05-11T20:10:15+00:00

So say I have this XML file: <?xml version=1.0 encoding=utf-8 standalone=yes?> <Root> <Category Name=Tasties>

  • 0

So say I have this XML file:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <Category Name="Tasties">
    <Category Name="Pasta">
      <Category Name="Chicken">
        <Recipe Name="Chicken and Shrimp Scampi" />
        <Recipe Name="Chicken Fettucini Alfredo" />
      </Category>
      <Category Name="Beef">
        <Recipe Name="Spaghetti and Meatballs" />
        <Recipe Name="Lasagna" />
      </Category>
      <Category Name="Pork">
        <Recipe Name="Lasagna" />
      </Category>
      <Category Name="Seafood">
        <Recipe Name="Chicken and Shrimp Scampi" />
      </Category>
    </Category>
  </Category>
</Root>

And I want to return the names of all the recipes in Tasties\Pasta\Chicken, how would I do this?

What I have currently is:

var q = from chk in
            (from c in doc.Descendants("Category")
             where c.Attribute("Name").Value == "Chicken"
             select c)
        select from r in chk.Descendants("Recipe")
               select r.Attribute("Name").Value;

foreach (var recipes in q)
{
    foreach (var recipe in recipes)
    {
        Console.WriteLine("Recipe name = {0}", recipe);
    }
}

Which kinda works, although it doesn’t check the path, only for the first category named Chicken. I could dig through each element in the path recursively, but it seems like there probably is a better solution I’m missing. Also my current query returns IEnumerable<IEnumerable<String>> when all I want is just an IEnumerable<String>.

Basically I can make it work but it looks messy and I’d like to see any LINQ suggestions or techniques to do better querying.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T20:10:15+00:00Added an answer on May 11, 2026 at 8:10 pm

    Personally, I’d use XmlDocument and the familiar SelectNodes:

    foreach(XmlElement el in doc.DocumentElement.SelectNodes(
       "Category[@Name='Tasties']/Category[@Name='Pasta']/Category[@Name='Chicken']/Recipe")) {
        Console.WriteLine(el.GetAttribute("Name"));
    }
    

    For LINQ-to-XML, I’d guess (untested) something like:

    var q = from c1 in doc.Root.Elements("Category")
            where c1.Attribute("Name").Value == "Tasties"
            from c2 in c1.Elements("Category")
            where c2.Attribute("Name").Value == "Pasta"
            from c3 in c2.Elements("Category")
            where c3.Attribute("Name").Value == "Chicken"
            from recipe in c3.Elements("Recipe")
            select recipe.Attribute("Name").Value;
    foreach (string name in q) {
        Console.WriteLine(name);
    }
    

    Edit: if you want the category selection to be more flexible:

        string[] categories = { "Tasties", "Pasta", "Chicken" };
        XDocument doc = XDocument.Parse(xml);
        IEnumerable<XElement> query = doc.Elements();
        foreach (string category in categories) {
            string tmp = category;
            query = query.Elements("Category")
                .Where(c => c.Attribute("Name").Value == tmp);
        }
        foreach (string name in query.Descendants("Recipe")
            .Select(r => r.Attribute("Name").Value)) {
            Console.WriteLine(name);
        }
    

    This should now work for any number of levels, selecting all recipes at the chosen level or below.


    Edit for discussion (comments) on why Where has a local tmp variable:

    This might get a bit complex, but I’m trying to do the question justice ;-p

    Basically, the foreach (with the iterator lvalue “captured”) looks like:

    class SomeWrapper {
        public string category;
        public bool AnonMethod(XElement c) {
            return c.Attribute("Name").Value == category;
        }
    }
    ...
    SomeWrapper wrapper = new SomeWrapper(); // note only 1 of these
    using(var iter = categories.GetEnumerator()) {
        while(iter.MoveNext()) {
            wrapper.category = iter.Current;
            query = query.Elements("Category")
                 .Where(wrapper.AnonMethod);
        }
    }
    

    It might not be obvious, but since Where isn’t evaluated immediately, the value of category (via the predicate AnonMethod) isn’t checked until much later. This is an unfortunate consequence of the precise details of the C# spec. Introducing tmp (scoped inside the foreach) means that the capture happens per iteration:

    class SecondWrapper {
        public string tmp;
        public bool AnonMethod(XElement c) {
            return c.Attribute("Name").Value == tmp;
        }
    }
    ...
    string category;
    using(var iter = categories.GetEnumerator()) {
        while(iter.MoveNext()) {
            category = iter.Current;
            SecondWrapper wrapper = new SecondWrapper(); // note 1 per iteration
            wrapper.tmp = category;
            query = query.Elements("Category")
                 .Where(wrapper.AnonMethod);
        }
    }
    

    And hence it doesn’t matter whether we evaluate now or later. Complex and messy. You can see why I favor a change to the specification!!!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

let's say, I have this xml file: <?xml version=1.0 encoding=UTF-8 ?> <TimeSeries> <timeZone>1.0</timeZone> <series>
Say I have an XML file which looks like this: <?xml version=1.0 encoding=UTF-8?> <Project
Lets say I have the following XML file: <?xml version=1.0 encoding=utf-8?> <Customers xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation=Customer.xsd>
lets say i have the following XML <?xml version=1.0 encoding=utf-8?> <names> <name first=John last=Doe/>
Say I have the following XML file: <?xml version=1.0 encoding=utf-8?> <venues> <group type=Nearby> <venue>
Say I have this given XML file: <root> <node>x</node> <node>y</node> <node>a</node> </root> And I
Let's just say I have an XML file that looks like this: <?xml version=1.0
I have a plist structured like this: <?xml version=1.0 encoding=UTF-8?> <!DOCTYPE plist PUBLIC -//Apple//DTD
Say I have an .xml file with a menu that looks like this. <?xml
Let's say I have this XML file. <book> <id>1</id> <title>Harry Potter - bla bla

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.