C#XML具有元素和属性的降序

时间:2015-04-01 09:32:04

标签: c# xml xpath linq-to-xml

我需要从xml文件中找到5个最多的学生

我的xml文件看起来像这样

<Professor id="Andy">
<Floor nb="1">
  <data>
    <Room>101</Room>
    <Nbstudent>33724</Nbstudent>
  </data>
      </Floor>
</Professor >
  <Professor id="Mick">
<Floor nb="2">
  <data>
    <Room>102</Room>
    <Nbstudent>33740</Nbstudent>
  </data>
  </Floor>
</Professor >

现在我的代码是

var xdoc = XDocument.Load("student.xml");
var student=
           (from r in xdoc.Descendants("data")
           orderby int.Parse(r.XPathSelectElement("Nbstudent").Value) descending
          select new
          {
           Name = r.XPathSelectElement("//Professor").Attribute("id").Value + "   ",
           Room= r.XPathSelectElement("Room").Value + "   ",
           NB= r.XPathSelectElement("Nbstudent").Value + "    ",
                  })
     .Take(5);
foreach (var r in student)
            {
                Console.WriteLine(r.Name + r.Room+ r.NB);
            }

它确实找到了我想要的5个值,但Name总是返回相同的值(即使不属于此属性的数据也是如此。

我不知道如何获取正确的属性。

3 个答案:

答案 0 :(得分:2)

使用原始代码进行最小更改来解决问题的另一种可能选项:

Name = r.XPathSelectElement("ancestor::Professor[1]").Attribute("id").Value + "   ",

答案 1 :(得分:1)

试试这个:

var student =
(from r in xdoc.Descendants("Professor")
orderby int.Parse(r.XPathSelectElement("Floor/data/Nbstudent").Value) descending
select new
{
    Name = r.Attribute("id").Value + "   ",
    Room = r.XPathSelectElement("Floor/data/Room").Value + "   ",
    NB = r.XPathSelectElement("Floor/data/Nbstudent").Value + "    ",
})
.Take(5);

请注意,您可以像这样简化整数解析:

var student =
(from r in xdoc.Descendants("Professor")
orderby (int)r.XPathSelectElement("Floor/data/Nbstudent") descending
select new
{
    Name = r.Attribute("id").Value + "   ",
    Room = r.XPathSelectElement("Floor/data/Room").Value + "   ",
    NB = r.XPathSelectElement("Floor/data/Nbstudent").Value + "    ",
})
.Take(5);

答案 2 :(得分:0)

    var student =
   (from r in xdoc.Descendants("Professor")
orderby int.Parse(r.XPathSelectElement("Floor/data/Nbstudent").Value) descending
select new
{
    Name = r.Attribute("id").Value + "   ",
    Room = r.XPathSelectElement("Floor/data/Room").Value + "   ",
    NB = r.XPathSelectElement("Floor/data/Nbstudent").Value + "    ",
})
.Take(5);