在Loop AS3中检查XML父项

时间:2013-06-26 15:46:09

标签: xml arrays actionscript-3

是否可以检查所有XML节点父项是否存在于某种循环中?假设我有一个参考:

myXML.sectionOne.subSectionOne.subsubSectionFive.subsubsubSectionTwo.name

我发现不仅name节点不存在,而且任何数量的父节点也可能不存在。所以我一直坚持做的事情就是:

if(myXML.sectionOne != undefined)
{
    if(myXML.sectionOne.subSectionOne != undefined)
    {
        if(myXML.sectionOne.subSectionOne.subsubSectionFive != undefined)
        {
            if(myXML.sectionOne.subSectionOne.subsubSectionFive.subsubsubSectionTwo != undefined)
            {
                if(myXML.sectionOne.subSectionOne.subsubSectionFive.subsubsubSectionTwo.name != undefined)
                {

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以编写递归函数来检查每个节点的localName()

var xml:XML = <root>
<sectionOne>
    <subSectionOne>
        <subsubSectionFive>
            <subsubsubSectionTwo>
                <name>bam!</name>
            </subsubsubSectionTwo>
        </subsubSectionFive>
    </subSectionOne>
</sectionOne>
</root>;

trace(hasNodeByName(xml,"name"));

function hasNodeByName(xml:XML,nodeName:String):Boolean{
    if(xml.localName() == nodeName) return true;//check root
    for each(var node:XML in xml.*){//check each node on 1st level
        if(node.localName() == nodeName) return true;
        else if(node.length() > 0) return hasNodeByName(node,nodeName);//we need to go deeper!
    }
    return false;   
}