如何通过属性值进行排序在LINQ XML文档? [英] How to sort XML document in linq by an attribute value?

查看:93
本文介绍了如何通过属性值进行排序在LINQ XML文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过排序属性的,没有运气值,我的XML文件。

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>



答的这里不为我工作。

我使用MVS 2010为Windows Phone 7。

I'm using MVS 2010 for Windows Phone 7.

我会感谢任何帮助。

! -

更新

感谢您的快速反应

juharr问一个很好的问题...我期待那排序依据将修改数据。现在我知道我错了。

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);



但我仍然一无所获。 数据是空的,它只包含<人/>

我不知道现在有什么错

我设法通过使用此代码来解决我的问题:

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);



是任何其他方式(更优雅)来修改数据使用排序依据,而不是创建 datatemp

推荐答案

我希望这可以帮助你。

var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id")).ToArray();

data.Descendants("person").Remove();
data.Element("persons").Add(people);



不要忘了用toArray()方法为你的

这篇关于如何通过属性值进行排序在LINQ XML文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆