我有这种XML层次结构
<Chapters>
<Chapter @num="">
<Section @letter="">
<Heading @num="" />
</Section>
</Chapter>
</Chapters>
我需要进行排序,以便所有章节按升序排序,该章节中的每个部分按升序排序,并且该部分中的每个标题都已排序......
执行以下操作会使章节正确排序,但显然未对子数据进行排序:
Dim chapsorted = From c In root.Elements
Order By c.@num Ascending
Select c
从那里我迷失了。我尝试了这个疯狂的事情来获得我想要的全部结果,但这对我没有任何好处:
Dim chapsorted = From c In root.Elements
Order By c.@num Ascending
Select (From sec In c.Elements Order By sec.@letter Where sec.Parent Is c Select
(From hed In sec.Elements Order By hed.@num Where hed.Parent Is sec)))
这对我也没有好处。
必须有一个简单的方法来做到这一点.... :-)帮助将非常感激,我已经旋转了几个小时。
答案 0 :(得分:1)
我认为你的第一个查询是正确的。通过从原始XElement
复制名称和属性,从结果排序节点列表中构造XElement
,然后嵌套该结构:
Dim chapsorted = New XElement(root.Name, _
root.Attributes, _
From c In root.Elements _
Order By c.@num Ascending _
Select New XElement(c.Name, _
c.Attributes, _
From s In c.Elements _
Order By s.@letter Ascending _
Select New XElement(s.Name, _
s.Attributes, _
From h In s.Elements _
Order By h.@num Ascending _
Select h)))
如果你在每个级别按相同的属性排序,你可以做这样的递归解决方案:
Private Function SortChildElements(ByVal element As XElement) As XElement
Return New XElement( _
element.Name, _
element.Attributes, _
element.Nodes.Where(Function(node) Not TypeOf node Is XElement), _
From child In element.Elements _
Order By child.@num Ascending _
Select SortChildElements(child))
End Function