简体   繁体   中英

How do I find the maximum value of an attribute value in an XML file?

I have an XML file with the following structure:

<doc>
  <rootelement>
     <childelement id="0" />
     <childelement id="1" />
     .
     .
  </rootelement>
</doc>

I want to find the highest numeric value of the id attribute

The idea I have in mind is something like:

int highest = -1;
foreach(var node in xmldoc.SelectNodes("//doc/rootelement/childelement"))
{
    highest = Math.Max(GetID(node), highest);
}

where GetID(XMLNode) would retrieve the value of the attribute of the current node.

Is there a more compact (or more efficient) XPath expression to do that?

You can use Linq to Xml:

var xdoc = XDocument.Load(path_to_xml);
var maxId = xdoc.XPathSelectElements("//doc/rootelement/childelement")
                .Max(c => (int)c.Attribute("id"));

Or without XPath:

var maxId = xdoc.Root.Elements("rootelement")
                .Elements("childelement")
                .Max(c => (int)c.Attribute("id"));

With XmlDocument:

var maxId = doc.SelectNodes("//doc/rootelement/childelement")
               .Cast<XmlElement>()
               .Max(c => Int32.Parse(c.Attributes["id"].Value));

Use Linq to XML.

string xml = 
    @"<doc>
    <rootelement>
        <childelement id='0' />
        <childelement id='1' />
    </rootelement>
    </doc>";

var doc = XDocument.Parse(xml);
int max = doc.Descendants("childelement").Max(e => (int)e.Attribute("id"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM