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>
I would like to move the tab with testing in it above Overview. How would I go about this using linq to XML?
You can move the elements by removing them and then reinserting them at the desired position:
var doc = XDocument.Parse(@"<tabs>...</tabs>");
var tab = doc.Root.Elements().ElementAt(1);
tab.Remove();
doc.Root.AddFirst(tab);
Alternatively, you can create a new document from the existing elements in the desired order:
var doc = XDocument.Parse(@"<tabs>...</tabs>");
var tabs = doc.Root.Elements();
var result = new XDocument(
new XElement("tabs",
tabs.ElementAt(1),
tabs.ElementAt(0),
tabs.ElementAt(2)));
I haven't tested it, but this might work:
void Swap(XElement a, XElement b)
{
var c = new XElement("dummy");
a.ReplaceWith(c);
b.ReplaceWith(a);
c.ReplaceWith(b);
}
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
You can use something like:
var tests = from node in doc.Descendants("name") where node.Value == "Testing" select node;
var test = tests.Single();
var tab = test.Parent;
var tabs = tab.Parent;
tab.Remove();
tabs.AddFirst(tab);
Not sure how much of your XML structure is fixed / known.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With