I'm trying to bind the results of a Linq to XML query to a DataList control and I'm having trouble returning all of the child values. Here's my XML...

<categories>
  <category>
    <parent-id>1234</parent-id>
    <parent-name>Parent 1</parent-name>
    <children>
      <child-cat>
        <child-id>5678</child-id>
        <child-name>Child 1</child-name>
      </child-cat>
      <child-cat>
        <child-id>2824</child-id>
        <child-name>Child 2</child-name>
      </child-cat>
      <child-cat>
        <child-id>2831</child-id>
        <child-name>Child 3</child-name>
      </child-cat>
    </children>
  </category>
  <category>
    <parent-id>6398</parent-id>
    <parent-name>Parent 2</parent-name>
    <children>
      <child-cat>
        <child-id>5564</child-id>
        <child-name>Child 1</child-name>
      </child-cat>
      <child-cat>
        <child-id>2824</child-id>
        <child-name>Child 2</child-name>
      </child-cat>
      <child-cat>
        <child-id>2831</child-id>
        <child-name>Child 3</child-name>
      </child-cat>
    </children>
  </category>

Here's my Linq query...

var categories = XDocument.Load(Server.MapPath("/app_data/ShoppingCategories.xml"));
        var allCats = from category in categories.Root.Descendants("category")
             select new
                      {
                          parentId = category.Descendants("parent-id").First().Value,
                          parentName = category.Descendants("parent-name").First().Value,
                          childId = category.Descendants("child-cat").First().Value,
                          childName = category.Descendants("child-name").First().Value
                      };
        dtlstCategories.DataSource = allCats; 
        dtlstCategories.DataBind();

My output looks like this (I'm only displaying the parent-name and child-name fields, the id fields are being bound to hidden fields)...

Parent 1   Parent 2
Child 1      Child 2

Because I'm using .First() on the child elements I realize this is why only the first are displaying, but I can't seem to figure out how to get them all to display. This is what I'm after...

Parent 1   Parent 2
Child 1      Child 1
Child 2      Child 2
Child 3      Child 3

It seems like I'm pretty close to getting what I want, but I just can't tie it all together. Any help is appreciated!

Related posts

Recent Viewed