XmlDocument, how to get all nodes that has the same name?

I have an xml file with a lot of nodes (at different node-levels) named “item”.

How can I retrieve a list of all nodes with nodename = “item”, creatively? I mean - I can always do a recursive search but that is not neat!

There where some nice .NET C# samples illustrating LINQ approach. But that doesn’t seem to work with Element RTL.

Thank you.

XmlElement.ElementsWithName

Thank you but I tried and it seems only search at one level depth, ie children of current element not multiple levels down?

I think the best would be to use XmlElement.ElementsWithName as the starting point. So I have the following enhanced method that returns AllElementswithName, internally it runs recursively :

  XmlDocumentHelper =  public extension class(XmlDocument)
  public
    method AllElementsWithName(aLocalName: not nullable String; aNamespace: nullable XmlNamespace := nil;
      aXmlElement: XmlElement := nil): not nullable sequence of XmlElement;
    begin
      var lXmlElement: XmlElement;
      
      if not assigned(aXmlElement) then 
        lXmlElement := Root
      else 
        lXmlElement := aXmlElement;
      
      if lXmlElement.Elements.Count = 0 then 
        exit(new List<XmlElement>);

      result := lXmlElement.ElementsWithName(aLocalName, aNamespace);
      
      for each el in lXmlElement.Elements do
        result := (not nullable sequence of XmlElement)(result.Concat(AllElementsWithName(aLocalName, aNamespace, el)));      
    end;
  end;

And to retrieve all elements of an xml document with a specified name, we now just call:

var xmlDoc: XmlDocument := XmlDocument.FromFile('MyHolyShit.xml');
// All elements in the xml doc with name "item" are returned.
var items := xmlDoc.AllElementsWithName('item'); 

This works but I wonder if there is any other more elegant way to accomplish this?

Oh, you want all child-elements, recursive? I’m afraid that’s the best option for that for now. I’ll see if I can add an overload…