AdvancedDataGridにXMLをdataProviderとして与えてツリー表示をする場合などに、HierarchicalDataを使います。
HierarchicalData#childrenFiedlで子ノードを格納する要素名を指定できるのですが、特に表示用に作ったわけでもないXMLである場合、子ノードを
格納する要素の名前が同じであるとは限りません。この場合、childrenFieldでは対応できなくなります。
そこで、子ノードの判定を行う関数を指定できるIHierarchicalDataの実装があると便利です。

というわけで作ってみました。コンストラクタで判定関数を指定できるようになっています。
あと、Xmlに特化している分、HierarchicalDataより高速に動くというメリットもあります。(たぶん)

import flash.events.EventDispatcher;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
import mx.collections.IHierarchicalData;

public class XmlHierarchicalData extends EventDispatcher implements IHierarchicalData
{
	private var _source:XMLList;
	private var getChildrenFieldName:Function;

	public function XmlHierarchicalData(value:XMLList, childrenNameFunc:Function) {
		source = value;
		getChildrenFieldName = childrenNameFunc;
	}

	public function get source():XMLList
	{
		return _source;
	}

	public function set source(value:XMLList):void
	{
		_source = value;

		var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
		event.kind = CollectionEventKind.RESET;
		dispatchEvent(event);
	}

	public function canHaveChildren(node:Object):Boolean
	{
		if (node == null) {
			return false;
		}
		var list:XMLList = getChildren(node) as XMLList;
		return list.length() > 0;
	}

	public function hasChildren(node:Object):Boolean
	{
		if (node == null) {
			return false;
		}
		var children:XMLList = XMLList(getChildren(node));
		return children.length() > 0;
	}

	public function getChildren(node:Object):Object
	{
		if ( node == null ) {
			return null;
		}
		var xml:XML = XML(node);
		var name:String = String(xml.localName());
		var childrenField:String = getChildrenFieldName(xml) as String;
		return xml.child(childrenField).*;
	}

	public function getData(node:Object):Object
	{
		return node;
	}

	public function getRoot():Object
	{
		return _source;
	}
}

Leave a Reply

(required)

(required)


+ 5 = eleven

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>