为什么Linq xml OrderBy不适合我?

时间:2012-12-27 16:45:15

标签: c# xml linq sql-order-by

我有以下XML文件:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <invoice xmlns="http://www.jemos.co.uk/xsds/experiments">
<header date="2012-12-27T13:17:03.652Z" invoiceId="0yFUWhwmHH">
    <seller name="euxz0bIqiC">
        <address line1="fxWDfaMu8O" line2="u5LmqdrH6f" line3="5c7XVSiXCh"
            city="CyCJOexD1v" postcode="Td4RmntPah" country="_vzVd1oo1Z" />
    </seller>
    <buyer name="UKNWLox8WE">
        <address line1="6RcK4QKz94" line2="U04UEsRMjh" line3="lnSWe9NY0r"
            city="g5nj0tbJbx" postcode="evyno9yUR6" country="rpIgh2XDIo" />
    </buyer>
</header>
<details>
    <items>
        <item id="ZBV9eUw0MS" description="h_x4Lqr2bp" quantity="1356614223664"
            price="0.552495629185551" currency="NdqzH508tA" />
        <item id="HNAQbfAXrv" description="sTgStzKny7" quantity="1356614223666"
            price="0.10527685341195969" currency="tvJUSZjipG" />
        <item id="ikJ0y_8TdZ" description="RUXb6n7cMJ" quantity="1356614223667"
            price="0.8693868918655814" currency="8LHywfSuC7" />
        <item id="lbdLaiI7zK" description="B_kId9Er07" quantity="1356614223668"
            price="0.9610746134524019" currency="bJvcOByXzx" />
        <item id="fBRl89ir8K" description="CuUiyjfFrz" quantity="1356614223669"
            price="0.6002495627735738" currency="WqB4AgH6Jv" />
    </items>
</details>

并获得以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XMLExperiments
{
class Program
{


    static void Main(string[] args)
    {

        XDocument xml = XDocument.Parse(Properties.Resources.test);
        IEnumerable<XElement> items = xml.Descendants()
            .Where(el => el.Name.LocalName.Contains("item"));

        foreach (XElement item in items)
        {
            IEnumerable<XAttribute> attrs = item.Attributes()
                .OrderBy(at => at.Name.LocalName);                  
            foreach (XAttribute attr in attrs)
               Console.WriteLine("Attribute name: {0}", attr.Name.LocalName);

        }

        Console.ReadKey();
    }
}
}

执行后,我得到以下内容:

enter image description here

我希望首先出现“货币”,而所有其他项目都是正确排序的。如果我下降,也会发生类似的情况。

任何指针?

1 个答案:

答案 0 :(得分:6)

根据您的输出,它看起来就像。

最后几行是:

currency  
description  
id  
price  
quantity  

在您的屏幕截图中,有4个地方存在“货币”,5个存在“数量”。所有事情都指向第一行只是从顶部滚动。