How to sort XML document in linq by an attribute value?
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
?
Based on the question you linked to, this works:
var people = from p in data.Elements("person")
orderby (string)p.Attribute("id")
select p;
or
var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id"));
(tested on a phone to confirm too.)
I hope this helps you
var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id")).ToArray();
data.Descendants("person").Remove();
data.Element("persons").Add(people);
Don't forget to use the ToArray() method for your people
.
精彩评论