我试图将 Linq to XML 查询的结果绑定(bind)到 DataList 控件,但在返回所有子值时遇到问题。这是我的 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>
这是我的 Linq 查询...
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();
我的输出看起来像这样(我只显示父名和子名字段,id 字段被绑定(bind)到隐藏字段)...
父级 1 父级 2
child 1 child 2
因为我在子元素上使用 .First() 我意识到这就是为什么只显示第一个元素的原因,但我似乎无法弄清楚如何让它们全部显示。这就是我所追求的......
父级 1 父级 2
child 1 child 1
child 2 child 2
child 3 child 3
我似乎离得到我想要的东西很近了,但我就是不能把它们联系在一起。感谢您的帮助!
编辑
这是我的数据列表...
<asp:DataList ID="dtlstCategories" runat="server" OnItemDataBound="dtlstCategories_ItemDataBound" Visible="True" RepeatColumns="5" RepeatDirection="Vertical" RepeatLayout="Table" ItemStyle-Wrap="True" BorderWidth="0" ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Top" ItemStyle-Width="170">
<ItemTemplate>
<div style="padding-left:10px; padding-right:10px;">
<asp:HiddenField ID="hdnTopCategoryId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "parentId") %>' />
<asp:LinkButton ID="lnkTopCategory" runat="server" CssClass="support" Text='<%#DataBinder.Eval(Container.DataItem, "parentName") %>'></asp:LinkButton>
<asp:Image ID="imgCatDivider" runat="server" />
<asp:HiddenField ID="hdnChildCatId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "childId") %>' />
<asp:LinkButton ID="lnkChildName" runat="server" CssClass="support" Text='<%#DataBinder.Eval(Container.DataItem, "childName") %>'></asp:LinkButton>
</div>
</ItemTemplate>
</asp:DataList>
最佳答案
我会这样写
var allCats = categories.Descendants("child-cat")
.Select(c => new
{
parentId = c.Parent.Parent.Element("parent-id").Value,
parentName = c.Parent.Parent.Element("parent-name").Value,
childId = c.Element("child-id").Value,
childName = c.Element("child-name").Value
})
.ToList();
关于c# - Linq to XML 选择所有父项和子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700325/