Get max attribute value from XML using LINQ

后端 未结 2 1094
旧巷少年郎
旧巷少年郎 2021-01-18 22:47

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,

相关标签:
2条回答
  • 2021-01-18 23:03

    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.

    0 讨论(0)
  • 2021-01-18 23:13
    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.

    0 讨论(0)
提交回复
热议问题