Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max attribute value from XML using LINQ

I have the following XML file. I want to get Max("NR") using LINQ. Could anyone help me to do this? I know how to do this for nodes, but attributes made me confused... :S

<?xml version="1.0" encoding="utf-8"?>
<SMPyramid LayerName="qwe" LayerPath="D:\#PYRAMID\qwe" Extension=".png" Meters="100000" RasterSize="4000">
  <Level NR="0" RasterXSize="512" RasterYSize="512" LastTileXSize="416" LastTileYSize="416" MinX="400000" MaxX="500000" MinY="1200000" MaxY="1300000" ScaleFactor="25" TilesCountX="8" TilesCountY="8" />
  <Level NR="1" RasterXSize="512" RasterYSize="512" LastTileXSize="323" LastTileYSize="323" MinX="400000" MaxX="499980.9024" MinY="1200019.0976" MaxY="1300000" ScaleFactor="34.679466666666663" TilesCountX="6" TilesCountY="6" />
  <Level NR="2" RasterXSize="512" RasterYSize="512" LastTileXSize="414" LastTileYSize="414" MinX="400000" MaxX="499738.14613333333" MinY="1200261.8538666666" MaxY="1300000" ScaleFactor="69.358933333333326" TilesCountX="3" TilesCountY="3" />
  <Level NR="3" RasterXSize="512" RasterYSize="512" LastTileXSize="206" LastTileYSize="206" MinX="400000" MaxX="499599.42826666665" MinY="1200400.5717333332" MaxY="1300000" ScaleFactor="138.71786666666665" TilesCountX="2" TilesCountY="2" />
  <Level NR="4" RasterXSize="358" RasterYSize="358" LastTileXSize="358" LastTileYSize="358" MinX="400000" MaxX="499321.99253333331" MinY="1200678.0074666666" MaxY="1300000" ScaleFactor="277.4357333333333" TilesCountX="1" TilesCountY="1" />
</SMPyramid>
like image 772
Nickon Avatar asked Oct 11 '12 13:10

Nickon


2 Answers

You treat attributes exactly the same way you would as nodes. So for example:

int maxNr = doc.Descendants("Level")
               .Max(x => (int) x.Attribute("NR"));

Note that that will give you the maximum value of NR, not the Level element which contains that number. For that, you'd want to either use OrderByDescending(...).First() or use MaxBy from MoreLINQ.

like image 188
Jon Skeet Avatar answered Nov 09 '22 16:11

Jon Skeet


XDocument xDoc = XDocument.Load(@" your XML file path ");
int maxNr = xDoc.Root.Elements().Max(x => (int)x.Element("NR"));

After you specify the file path, you can get "NR" using the Element.

like image 37
RuudVanNistelrooy Avatar answered Nov 09 '22 16:11

RuudVanNistelrooy