views:

183

answers:

5

I have XML that looks like this:

<question>
    <type_elt>
        <opt_out_flag />
    </type_elt>
</question>

type_elt is not an element name; it might be <single>, <multiple> or something else, determined at runtime. How, given this, can I detect the presence of the opt_out_flag element?

I tried this (where xml refers to the question element):

if (xml.*.opt_out_flag) {
    do_something();
}

but even in cases without opt_out_flag the above expression returns true. Obviously I'm missing something, but what is it?

+1  A: 

I believe you want to use xml.*.hasOwnProperty('opt_out_flag') rather than what you're currently using.

quoo
A: 

Can you be guaranteed that <opt_out_flag/> will always be in the first child of the <question> element? If so, something like the following should work:

(disclaimer: I know this works with attributes, but I don't know if it will work with child elements)

if( "opt_out_flag" in xml.children()[0] ) {
    doSomething();
}
Dan
I can't guarantee that, no. The grammar for the XML I am processing is underspecified and sort of ad-hoc, making it hard, if not impossible, to make solid assertions about the ordering or content of elements.
Chris R
Ahh OK. Then I would think that quoo's solution is probably the way you need to go then. If that solution doesn't work, you may be forced to loop through every child element, testing for the existence of the opt-out flag - not pretty!
Dan
+2  A: 

Try this

xml..opt_out_flag

It will search for all occurrence

Rahul Garg
A: 

Hi, can you use the descendants method (which recurses down the tree) to find the tag?

var optOutNodes:XMLList = xml.descendants("opt_out_flag");

if(optOutNodes.length())
{
   //do code here
}

Hope this is what you are looking for.

A: 

You can use

var optOut:Boolean = xml..opt_out_flag != undefined

you can omit the != undefined part, but I would leave it there for readability.

sharvey