LINQ到XML:什么是移动节点上下的最有效方法 [英] LINQ to XML: What is the most effective way to move nodes up and down
本文介绍了LINQ到XML:什么是移动节点上下的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要之前某些节点后移到同级节点。在这里,以
I need to move sibling nodes before and after certain nodes. Here is the code im working with
<tabs>
<tab>
<name>Overview</name>
</tab>
<tab>
<name>Testing</name>
</tab>
<tab>
<name>Performance</name>
</tab>
<tab>
<name>Braking</name>
</tab>
</tabs>
我想上面概述其测试移动标签。我怎么会去这样使用LINQ to XML?
I would like to move the tab with testing in it above Overview. How would I go about this using linq to XML?
推荐答案
对不起,这是VB.NET和XML文本,但它可以完成老同学在C#。这里的想法是使用反向
延伸方式:
Sorry, this is VB.NET and XML Literals, but it can be done old school in C#. The idea here is to use the Reverse
extention method:
Sub Main()
Dim tab = <tabs>
<tab>
<name>Overview</name>
</tab>
<tab>
<name>Testing</name>
</tab>
<tab>
<name>Performance</name>
</tab>
<tab>
<name>Braking</name>
</tab>
</tabs>
Console.WriteLine(SwapElements("Testing", "Performance", tab).ToString)
Console.ReadLine()
End Sub
Function SwapElements(ByVal firstElement As String, ByVal secondElement As String, ByVal tab As XElement) As XElement
Dim swapped = tab.Elements.Where(Function(e) e.Value = firstElement Or e.Value = secondElement).Reverse
Dim middle = tab.Elements.SelectMany(Function(e) e.ElementsAfterSelf.Where(Function(f) e.Value = firstElement).TakeWhile(Function(g) g.Value <> secondElement))
swapped.ElementAt(0).AddAfterSelf(middle)
Return <<%= tab.Name %>>
<%= tab.Elements.Select(Function(e) e.ElementsBeforeSelf.Where(Function(f) e.Value = firstElement)) %>
<%= swapped %>
<%= tab.Elements.Select(Function(e) e.ElementsAfterSelf.Where(Function(f) e.Value = secondElement)) %>
</>
End Function
这篇关于LINQ到XML:什么是移动节点上下的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文