Get max attribute value from XML using LINQ

怎甘沉沦 提交于 2019-12-30 18:57:05

问题


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>

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12840647/get-max-attribute-value-from-xml-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!