如何在AS3中显示具有特定属性的节点的XML后代?

时间:2011-02-22 16:44:04

标签: xml actionscript-3 variables nodes

我一直在试图弄清楚如何显示具有特定属性的父节点的后代(在本例中为exchangeRate和PlacesOfInterest)。

要设置场景 - 用户单击将字符串变量设置为目标的按钮,例如。日本或澳大利亚。

然后代码通过XML中的一组节点运行,并且跟踪任何具有匹配属性的节点 - 足够简单

我无法弄清楚的是如何只显示具有该属性的节点的子节点。

我确信必须有这样做的方法,当我找到它时,我可能会撞到桌子上,但任何帮助都会非常感激!

public function ParseDestinations(destinationInput:XML):void 
    {
        var destAttributes:XMLList = destinationInput.adventure.destination.attributes();

        for each (var destLocation:XML in destAttributes) 
        {               
            if (destLocation == destName){
                trace(destLocation);
                trace(destinationInput.adventure.destination.exchangeRate.text());
            }
        }
    }



<destinations>
    <adventure>
        <destination location="japan">
            <exchangeRate>400</exchangeRate>
            <placesOfInterest>Samurai History</placesOfInterest>
        </destination>   
        <destination location="australia">
            <exchangeRate>140</exchangeRate>
            <placesOfInterest>Surf and BBQ</placesOfInterest>
        </destination>
    </adventure>
</destinations>

2 个答案:

答案 0 :(得分:0)

您应该能够在as3中轻松地使用E4X过滤节点:

 var destinations:XML = <destinations>
    <adventure>
        <destination location="japan">
            <exchangeRate>400</exchangeRate>
            <placesOfInterest>Samurai History</placesOfInterest>
        </destination>   
        <destination location="australia">
            <exchangeRate>140</exchangeRate>
            <placesOfInterest>Surf and BBQ</placesOfInterest>
        </destination>
    </adventure>
</destinations>;
//filter by attribute name
var filteredByLocation:XMLList = destinations.adventure.destination.(@location == "japan");
trace(filteredByLocation);
//filter by node value
var filteredByExchangeRate:XMLList = destinations.adventure.destination.(exchangeRate < 200);
trace(filteredByExchangeRate);

有关详细信息,请查看Yahoo! devnet articleRoger's E4X article

相关的stackoverflow问题:

HTH

答案 1 :(得分:0)

如果您不知道后代的名字,或者您想要选择具有相同属性值的不同后代,您可以使用:

destinations.descendants(&#34; *&#34;)。elements()。(属性(&#34; location&#34;)==&#34; japan&#34;);

例如:

var xmlData:XML = 
<xml>
    <firstTag>
        <firstSubTag>
            <firstSubSubTag significance="important">data_1</firstSubSubTag>
            <secondSubSubTag>data_2</secondSubSubTag>
        </firstSubTag>   
        <secondSubTag>
            <thirdSubSubTag>data_3</thirdSubSubTag>
            <fourthSubSubTag significance="important">data_4</fourthSubSubTag>
        </secondSubTag>
    </firstTag>
</xml>


trace(xmlData.descendants("*").elements().(attribute("significance") == "important"));

结果:

//<firstSubSubTag significance="important">data_1</firstSubSubTag>
//<fourthSubSubTag significance="important">data_4</fourthSubSubTag>