I've tried to sort my xml file by attribute's value with no luck.
data.Descendants("person").OrderBy(x => x.Attribute("id").Value);
data contains:
<persons>
<person id="1">
<name>Abra</name>
<age>25</age>
</person>
<person id="2">
<name>Cadabra</name>
<age>29</age>
</person>
<person id="4">
<name>Hokus</name>
<age>40</age>
</person>
<person id="3">
<name>Pokus</name>
<age>30</age>
</person>
</persons>
Answer given here does not work for me.
I'm using MVS 2010 for Windows Phone 7.
I would be grateful for any help.
--
Update
Thank You for quick responses!
juharr asked a good question... i was expecting that OrderBy
would modify data
. Now i know i was wrong.
I want to modify data
and i've done as follows (thanks Matt Lacey):
var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id"));
data.Descendants("person").Remove();
data.Element("persons").Add(people);
but i still got nothing. Data
is empty, it contains only <persons />
I wonder what's wrong now.
I manage to solve my problem by using this code:
XDocument datatemp = new XDocument(data);
var people = datatemp.Descendants("person").OrderBy(x => (int)int.Parse(x.Attribute("id").Value));
data.Descendants("person").Remove();
data.Element("persons").Add(people);
Is any other way (more elegant) to modify data
using OrderBy
instead of creating datatemp
?