Vince Ricosti
Vince Ricosti

Reputation: 519

Linq to Xml : sort xml nodes in function of an optional attribute

I would like to sort some xml node described below in function of an optional attribute

<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/">
<head>
    <meta name="dtb:uid" content="http://www.hxa7241.org/articles/content/epup-guide_hxa7241_2007_1.epub" />
</head>
<docTitle>
    <text>Roméo et Juliette</text>
</docTitle>
<navMap>
    <navPoint id="toc" playOrder="2">
        <navLabel>
            <text>Table des Matières</text>
        </navLabel>
        <content src="9789999997049_toc.html" />
    </navPoint>
    <navPoint id="tp" playOrder="1">
        <navLabel>
            <text>Page de Titre</text>
        </navLabel>
        <content src="9789999997049_tp.html" />
    </navPoint>
    <navPoint id="p01" playOrder="3">
        <navLabel>
            <text>ACTE PREMIER</text>
        </navLabel>
        <content src="9789999997049_p01.html" />
        <navPoint id="ch02" playOrder="5">
        <navLabel>
          <text>Sc&#232;ne 2</text>
        </navLabel>
        <navPoint id="ch01" playOrder="4">
            <navLabel>
                <text>Scène première</text>
            </navLabel>
            <content src="9789999997049_ch01.html" />
        </navPoint>
        <content src="9789999997049_ch02.html"/>
     </navPoint>
    </navPoint>
</navMap>

How can I sort the navpoint nodes in function of playOrder attribute if it exists and retrieve the xml normally if it doesn't ? Should I first test if playOrder exists and then make a different Linq query or is it possible to handle everything (with maybe a case) with a single statement ?

Upvotes: 1

Views: 251

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503210

It's easiest to just cast to a nullable type and order by that:

var sorted = navPoints.OrderBy(x => (int?) x.Attribute("playOrder"));

That will give the null value if the attribute doesn't exist; all those entries would end up coming first (IIRC) in the sorted collection.

Upvotes: 1

Related Questions