문제

I want to create a utility function that requires accessing XML children nodes dynamically.

Sample XML:

var xml:XML = 
<root>
    <section>
        <lt target='foo'/>
        <lt target='foo1'/>
        <lt target='foo2'/>
    </section>
    <section1>
        <lt target='foo'/>
        <lt target='foo1'/>
        <lt target='foo2'/>
    </section1>
</root>;

I want to be able to access all the 'lt' nodes regardless of its parent node. Normally, you would do that like this:

var xList:XMLList = xml..lt;

//Output

xList = 
<lt target='foo'/>
<lt target='foo1'/>
<lt target='foo2'/>
<lt target='foo'/>
<lt target='foo1'/>
<lt target='foo2'/>

That works fine, however, I need to access the 'lt' node not knowing the name up front. For instance...

var nodeName:String = 'lt';
var xList:XMLList = xml..[nodeName]; //<-- Does not work.

I was hoping to get this done without using a for loop. Any ideas?

Thanks,

Victor

도움이 되었습니까?

해결책

You probably just need:

 var nodeName:String = "lt";
 var xList:XMLList = xml.descendants( nodeName );

다른 팁

Assuming they're all the same depth into your xml, you can use * as a wildcard. For example:

var xml:XML = <root>
    <obj1>
        <test>a</test>
    </obj1>
    <obj2>
        <test>b</test>
    </obj2>
    <obj2>
        <lala>
            <test>c</test>
        </lala>
    </obj2>
</root>;
trace(xml.*.test);

Traces out:

<test>a</test>
<test>b</test>

xml.children().test would do the same thing, by the way.

You want to use the E4X parenthetical operators, also called filters. And also use a wildcard operator to return all children. Very powerful, it will allow you to search by using a string.

trace("trace",xml..*.(localName() =='lt'));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top