2 Replies Latest reply on Sep 6, 2007 11:42 AM by aceinc

    Looping through XML tree

    aceinc Level 1
      I have posted this under Flex General support under a different title.

      What I am trying to do is to loop through an XML structure that is used as a dataprovider for a menubar. I have been unable to find how to do this. Some of what I have tried so far is;

      I think I can get the data in XML format using;

      MenuData = XML(menuLoad.lastResult);

      Once in this format I have been unable to find a way to loop (recursively, I presume) through the children to find the child with the attribute I need.

      I have looked through documentation, forums, blogs etc. and no one (that I could find) has an example of how to loop through an XML tree. Here is an example that does not work;

      traceNodes(MenuData);

      private function traceNodes(theNode:XML):void
      {
      for(var child in theNode.)
      {
      trace(child.name());
      trace(child.attributes());
      traceNodes(theNode[child]);
      }
      }

      I really need help on this one.

      Paul

        • 1. Re: Looping through XML tree
          Senor_Roberto
          You should simply be able to use E4X notation to traverse the tree.

          E.g. if your XML was:

          var dummyXml:XML = <tests><test id='1'/><test id='2'/><test id='3'/></tests>;

          You could then:

          // dummyXML.test gives you each child 'test' node as 'tests' is the root
          for each (var x:XML in dummyXML.test) {
          ...
          }

          Can you post the XML you're using as the data provider?

          Or am I misunderstanding?
          • 2. Re: Looping through XML tree
            aceinc Level 1
            Roberto:

            Thanks for the post, I was eventually able to resolve this. Below is my function to find a node in an xml tree. You might call it like this;

            xmlMyNode = getXMLByAttribute(xmlMytree,"*","label","My Label");

            -----------------------------------------------------------

            private function getXMLByAttribute(xmlInputNode:XML,strNodeName:String,strAttribute:String,strAttributeVal ue:String):XML
            {
            var xmlReturnNode:XML = null;
            for each (var xmlCurrentNode:XML in xmlInputNode[strNodeName])
            {
            if (xmlCurrentNode.@[strAttribute] == strAttributeValue) return xmlCurrentNode;
            xmlReturnNode = getXMLByAttribute(xmlCurrentNode,strNodeName,strAttribute,strAttributeValue);
            if (xmlReturnNode != null) break;
            }
            return xmlReturnNode;
            }


            Paul