[英]C# XML Descending order with elements and attributes
我需要從一個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總是返回相同的值(即使之后的數據不屬於此屬性。
我不知道如何獲得正確的屬性。
可以通過最小程度地更改原始代碼來解決問題的另一種可能的選擇:
Name = r.XPathSelectElement("ancestor::Professor[1]").Attribute("id").Value + " ",
嘗試這個:
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);
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.