Search code examples
actionscript-3flashactionscript

How can I find only base nodes of an XML file


I have an xml file with various nodes and want to get first nodes of it, not children. Here's my code:

function processXML(event:Event):void {
    menu_xml = new XML(event.target.data);
    trace (menu_xml.child("mainmenu"));
}

This code doesn't display anything. I'm using Flash Professional CC 2015.0.

EDIT: Here's the xml content:

<?xml version="1.0"?> 
<mainmenu>

    <home/> 
    <portfolio/> 
    <contact/> 
    <friends>

        <joe/> 
        <karen/> 
        <bob/> 

    </friends>

</mainmenu>

EDIT 2: I need to get only these strings: home, portfolio, contact, friends.


Solution

  • Your variable menu_xml is the base node, by calling menu_xml.child("mainmenu") you are seeking for XML like this:

    <mainmenu>//menu_xml
        <mainmenu/>//menu_xml.child("mainmenu");
    </mainmenu>
    

    Obviously this doesn't exist and the function returns an empty XML record. Your data set:

    <mainmenu>//menu_xml = new XML(event.target.data);
    
        <home/>//menu_xml.child("home"); 
        <portfolio/> //menu_xml.child("portfolio"); 
        <contact/> //menu_xml.child("contact"); 
        <friends>//menu_xml.child("friends"); 
    
            <joe/> //menu_xml.child("friends").child("joe"); 
            <karen/> //menu_xml.child("friends").child("karen"); 
            <bob/> //menu_xml.child("friends").child("bob"); 
    
        </friends>
    
    </mainmenu>
    

    EDIT: To get the node names you will have to loop through the XML object structure, by looping through the result of the children() you will be able to use the name() function to get the name of each child of the root

    for each (var node:XML in menu_xml.children())
    {
        trace(node.name());
    }
    

    output:

    home
    portfolio
    contact
    friends
    

    For more information about Traversing XML structures in AS3, I recommend the AS3 Documentation