Reputation: 355
I want to sort the XML elements in ascending order based on the values of the inner attributes "Top".
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Designer>
<Sequence>
<Left>603.875</Left>
<Top>312.665</Top>
<total>NaN</total>
<Width>58.5</Width>
<Height>45.5</Height>
<ID>635b1aed-6ee3-4cf5-9324-b0246f3a0c1d</ID>
<zIndex>0</zIndex>
<IsGroup>false</IsGroup>
<ParentID>00000000-0000-0000-0000-000000000000</ParentID>
<ItemLabel>123</ItemLabel>
</Sequence>
<Sequence>
<Left>568.875</Left>
<Top>29.664999999999992</Top>
<total>NaN</total>
<Width>58.5</Width>
<Height>45.5</Height>
<ID>9dd9a96d-4356-49c6-85a3-6b898983e688</ID>
<zIndex>1</zIndex>
<IsGroup>false</IsGroup>
<ParentID>00000000-0000-0000-0000-000000000000</ParentID>
<ItemLabel>321</ItemLabel>
</Sequence>
</Designer>
<Parameters>
<Value>
<Name> Label 1 </Name>
<ID> 1 </ID>
</Value>
<Value>
<Name> Label 2 </Name>
<ID> 2 </ID>
</Value>
</Parameters>
</Root>
And here is my code which I have tried.
try
{
XElement root = XElement.Load(MainWindow.Container.globalfilename +".xml");
var orderedtabs = root.Elements("Designer").Elements("Sequence")
.OrderBy(xtab => (float)xtab.Element("Top"))
.ToArray();
foreach (XElement tab in orderedtabs)
{
root.Add(tab);
}
root.Save("xmlfile" + ".xml");
MessageBox.Show("Sorted");
}
While I try to create a new XML file, tag gets deleted. but i can able to write in order from . However, and elements of it gets deleted.
Kindly provide me answers or corrections where I am going wrong.
Thank you in advance.
Upvotes: 1
Views: 3042
Reputation: 2641
Your Root, Designer and Parameters tags get deleted because you select only the Sequences tags which you then add to the top of you root. I suggest to remove all Sequences tags below Designer and reinsert the ordered Sequences under Designer again:
XElement root = XElement.Load("input.xml");
// Extract Sequences ordered by 'Top'
var orderedtabs = root.Elements("Designer").Elements("Sequence")
.OrderBy(xtab => (float)xtab.Element("Top"))
.ToArray();
// Remove Sequences from xml
root.Descendants("Designer").Elements("Sequence").Remove();
// Reinsert Sequences in new order under the Designer element
XElement designer = root.Descendants("Designer").FirstOrDefault();
foreach (XElement tab in orderedtabs)
{
designer.Add(tab);
}
root.Save("xmlfile" + ".xml");
Upvotes: 1