Question

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);
}
Was it helpful?

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.

OTHER TIPS

Do you want all the nodes of the same name from different parents to be joined in one XML structure? In that case, what you can do is this:

    public static function getNodesByName(myXML_:XMLList, nodeName_:String) : XMLList {
        var result:XMLList = new XMLList();
        for (var i1:Number = 0; i1 < myXML_.children().length(); i1++ ) {
            if (myXML_.children()[i1].name() == nodeName_) {
                result += myXML_.children()[i1].valueOf();
            } else if (myXML_.children()[i1].children()) { 
                result += getNodesByName(XMLList(myXML_.children()[i1].valueOf()), nodeName_);
            }
        }
        return result;
    }

It will return you XMLList with all nodes that have specified name. Use it like this:

var nodesList:XMLList = getNodesByName(myXML.children(), "myNodeName").valueOf();

If you want to turn that list into XML then:

var myXMLListTurnedIntoXML:XML = XML("<xml></xml>");
myXMLListTurnedIntoXML.appendChild(getNodesByName(myXML.children(), "myNodeName").valueOf());

Hope that will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top