如何检索xml节点根/顶级父级

时间:2012-01-03 06:21:41

标签: xml actionscript-3 flex air flex4.5

您好如何在actionscript中检索xml节点的顶级父级?

    <companies>
        <company id="1" name="boo" level="1">
            <company id="2" name="hoo" level="2">
                <company id="3" name="ooo" level="3"/>
            </company>
        </company>
    </companies>

提前感谢。

1 个答案:

答案 0 :(得分:1)

编辑(最终):

我想我得到了你的要求:company.(@level = 1)节点作为一个孩子选择company.(@level = 3)是什么。这也称为所选节点的“祖先”。 AS3 XML没有强大的祖先语法,因此您必须手动向上步。

对于未知级别的育儿,请使用类似this post discuss中的注释的循环。请注意,以下代码使用id属性进行搜索。这是因为所有id在单个XML中必须是唯一的,因此您可以保证找到该ID。

var xml:XML = <companies>
        <company id="1" name="boo" level="1">
            <company id="2" name="hoo" level="2">
                <company id="3" name="ooo" level="3"/>
            </company>
        </company>
        <company id="4" name="boo" level="1">
            <company id="5" name="hoo" level="2">
                <company id="6" name="ooo" level="3"/>
            </company>
        </company>
        <company id="7" name="boo" level="1">
            <company id="8" name="hoo" level="2">
                <company id="9" name="ooo" level="3"/>
            </company>
        </company>
    </companies>

// just for testing:
var selectedNodeXML:XML = 
    <company id="8" name="hoo" level="2" />

var selectedID:String = selectedNodeXML.@id;
trace("selectedID = " + selectedID);

var ancestorID:String = "";

for each( var companyNode:XML in xml.elements("*") )
{
    trace( "searching: " + companyNode.toXMLString() );  
    trace( "res: " + (companyNode..company.(@id == selectedID).@id == selectedID));
    if(
       companyNode.@id == selectedNodeXML.@id
       //|| companyNode.contains(selectedNodeXML) // You can use this if nothing gets messed up . . .
       || companyNode..company.(@id == selectedID).@id == selectedID // . . . but I think this is more reliable.
    ){
        ancestorID = companyNode.@id.toString();
        break;
    }
}

trace( "significant ancestor ID: " + ancestorID );