views:

774

answers:

3

Given this document:

<doc>
    <element>
        <list>
            <key attr='val'/>
        </list>
    </element>
    <element>
        <list>
            <key attr='other'/>
        </list>
    </element>
    <element>
        <list/>
    </element>
</doc>

I want an e4x equivalent of the xpath //element[list/key/@attr="val"]. Is it possible to do that?

+2  A: 
xmlVarName.element.list.key.(@attr=="val");

alternative

xmlVarName..key.(@attr=="val");
invertedSpear
No, that will return the key nodes. The xpath I showed returns the element nodes that have a particular key attribute.
Chris R
`//element` isn't `.element` (which is `/element`). It would be `..element`.
Eli Grey
I misunderstood what you were looking for, sorry, not familiar with xpath. Elijah has an answer, another is to call the parent() method like xmlVarName.element.list.key.(@attr=="val").parent().parent() (though Elijah's is cleaner).
invertedSpear
+1  A: 
..element.(list.key.@attr == "val")
Eli Grey
What will that do in cases where a key element exists without an @attr attribute? I know that XPath returns no node for that, but e4x craters with a missing attribute error type for simple expressions. Does that happen here, too?
Chris R
In my experience if the attribute is missing nothing will be returned, no error will be thrown.
invertedSpear
This will cause no problems in AS3. There is one issue in JavaScript. As long as the attribute is being checked on a child node (whether that even exists or not) in the filter, no errors will be thrown. `..(@bar=="baz")` would throw an error as not every element has a `bar` attribute, so you would want to try `..(function::attribute("bar")=="baz")` in JavaScript.
Eli Grey
A: 

It is important to note that

..element.(list.key.@attr == "val")

Can fail if the key nodes don't all have @attr.

The safest (although in my experience, not 100% successful) method to extract your node list would be.

..element.(list.key.attribute("attr") == "val")

However, I have had problems with e4x and conditional expressions, (AS3 implementation, Mozilla seems better.) but it seems to be down to the xml source.

slomojo