【问题标题】:FLEX - Check if parent() exists?FLEX - 检查 parent() 是否存在?
【发布时间】:2012-01-19 11:41:06
【问题描述】:

我需要访问我的 XML 中的信息。

我需要的信息不是存储在我的 XML 中的每个对象上,而是存储在父对象上。但是如何检查是否有父对象,以便在选择树中的第一个对象(没有父对象)时不会抛出错误?

这是我现在使用的代码,它适用于除了没有父对象的所有对象。

        public function getParentItem():String{
            var selectedItem:XML = treeView.selectedItem;

            while(selectedItem.@Close == ""){
                selectedItem = selectedItem.parent();
            }

            return selectedItem.@Close;

        }

我想我会添加一个 if 循环来检查父级是否存在,但不知道该怎么做。

谢谢!

【问题讨论】:

    标签: flash actionscript-3 apache-flex


    【解决方案1】:

    以下内容对您有用吗:

    public function getParentItem():String{
        var selectedItem:XML = treeView.selectedItem;
    
        while(selectedItem)
        {
            var closeAttribute:String = selectedItem.@Close;
    
            if(closeAttribute && closeAttribute != "") return closeAttribute;
            else selectedItem = selectedItem.parent();
        }
    
        return null;
    }
    

    基本上,它应该沿着 XML 树向上查找一个节点,该节点的“关闭”属性值为“无”。如果 XML 节点没有父节点,它将停止(在这种情况下,它将返回 null)。

    或者这里是递归完成的相同功能(为什么不!);)

    public function getParentItem() : String
    {
        return findCloseAttribute(XML(treeView.selectedItem));
    }
    
    private function findCloseAttribute(xml:XML) : String
    {
        if(xml)
        {
            var closeAttribute:String = xml.@Close;
    
            if(closeAttribute && closeAttribute != "") return closeAttribute;
            else return findCloseAttribute(xml.parent());
        }
        else
        {
             return null;
        }
    }
    

    【讨论】:

    • 感谢您快速而良好的回复。我会通读它,看看你做了什么。现在我使用 try-catch 来处理它。非常感谢您的时间和帮助!
    • 如果您知道可能会发生错误但您无法真正控制错误的来源,则尝试使用 catch 块很有用。在这种情况下,您始终可以避免使用 null 引用,因此我强烈建议您使用 @Richie_W 解决方案而不是 try catch
    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2010-11-15
    • 2015-11-09
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2018-09-10
    相关资源
    最近更新 更多