Search code examples
xmlactionscript-3xml-parsinge4x

Abstract way to get a XMLList of child nodes by name


I'm trying to build an abstract method to get all the nodes in an XML object by node name. I don't know the structure of the XML ahead of time.

So with this code I would like to get a list of all "item" nodes and all "x" nodes:

var xml:XML = <root><items><item/><item/><item><x/><item><item><x/></item></items></root>
var nodeName:String;
var list:XMLList;


list = getNodeByName(xml, "item"); // contains no results
list = getNodeByName(xml, "x"); // contains no results

// what am i doing wrong here?
public static function getNodeByName(xml:XML, nodeName:String):XMLList {
     return xml.child(nodeName);
}

Solution

  • As the name of the method says, child will only return a list of the children of the XML object matching the given parameter. if you want to get all descendants(children, grandchildren, great-grandchildren, etc.) of the XML object with a given name you should use descendants method:

    public static function getNodeByName(xml:XML, nodeName:String):XMLList {
         return xml.descendants(nodeName);
    }
    

    Hope it helps.