Pep
Pep

Reputation: 2027

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?

Upvotes: 3

Views: 4732

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

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));

Upvotes: 4

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

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"));

Upvotes: 1

Related Questions