3

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?

Pep
  • 1,957
  • 2
  • 24
  • 40

2 Answers2

4

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));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Is there a variant that also accomplishes this with XmlDocument instead of XDocument? I already have an XmlDocument created and converting everything from XmlDocument to XDocument in the current code (for the sake of consistency) would require a bit of refactoring. – Pep Mar 12 '14 at 11:30
  • @Pep sure you can (I'll update answer in a minute) but Linq to Xml is a preferred way to work with xml – Sergey Berezovskiy Mar 12 '14 at 11:32
  • That be great, thanks. I was precisely reading http://stackoverflow.com/questions/1542073/xdocument-or-xmldocument right now, and since we are writing a .NET 4.0 plugin, I do not see any drawback going for a future refactoring to use XDocument instead. – Pep Mar 12 '14 at 11:40
1

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"));
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68