I'm working with the following XML. In reality this will have many product nodes, but I think for the purpose of this post only one will do. I'd like to bind all of the child-product nodes to a DataList in my .aspx page, but I can't figure out how to convert the data returned from the Linq query to string values I can bind to the list. Can someone please provide some assistance?

<category>
    <product>
        <sku>2233</sku>
        <name>Item Name</name>
        <price>0.99</price>
        <description>Item Description</description>
        <children>
            <child-product>
                <child-sku>1234</child-sku>
                <child-name>Blue</child-name>
                <child-price>0.99</child-price>
            </child-product>
            <child-product>
                <child-sku>5678</child-sku>
                <child-name>Red</child-name>
                <child-price>0.99</child-price>
            </child-product>
            <child-product>
                <child-sku>9012</child-sku>
                <child-name>Green</child-name>
                <child-price>0.99</child-price>
            </child-product>
        </children>
    </product>
</category>

I'm trying to bind all of the child-product nodes to a DataList control in my .aspx page...

<asp:DataList ID="childItems" runat="server">
    <ItemTemplate>
        <asp:Label ID="lblChildSku" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "childSku") %>'></asp:Label>
        <asp:Label ID="lblChildName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "childName") %>'></asp:Label>
        <asp:Label ID="lblChildPrice" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "childPrice") %>'></asp:Label>
    </ItemTemplate>
</asp:DataList>

I'm querying the XML to return only the child-product nodes for a give parent (sku)...

var products = XElement.Load(Server.MapPath("/app_data/productList.xml"));
var childDetails = from child in products.Descendants("product")
    where (string)child.Element("sku").Value == strSku
    from childProducts in products.Descendants("child-product")
    select new
    {
        childSku = childProducts.Elements("child-sku"),
        childName =  childProducts.Elements("child-name"),
        childPrice = childProducts.Elements("child-price")
    }
childItems.DataSource = childDetails;
childItems.DataBind();

I would like the resulting DataList to look like:

1234 Blue 0.99
5678 Red 0.99
9012 Green 0.99

This is what I'm getting...

System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11 System.Xml.Linq.XContainer+d__11

I'm obviously very new working with Linq to XML and I'm having a very tough time figuring this out. Any help is much appreciated. Thanks.

Related posts

Recent Viewed