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?

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

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 sure you can (I'll update answer in a minute) but Linq to Xml is a preferred way to work with xml
That be great, thanks. I was precisely reading 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.
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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.