0

是否可以检查所有 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)
                {

                }
            }
        }
    }
}
4

1 回答 1

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;   
}
于 2013-06-26T16:36:16.120 回答