4

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?

Chris R
  • 17,546
  • 23
  • 105
  • 172

3 Answers3

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

alternative

xmlVarName..key.(@attr=="val");
invertedSpear
  • 10,864
  • 5
  • 39
  • 77
  • No, that will return the key nodes. The xpath I showed returns the element nodes that have a particular key attribute. – Chris R Jan 16 '10 at 14:18
  • `//element` isn't `.element` (which is `/element`). It would be `..element`. – Eli Grey Jan 17 '10 at 22:43
  • 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 Jan 18 '10 at 14:57
2
..element.(list.key.@attr == "val")
Eli Grey
  • 35,104
  • 14
  • 75
  • 93
  • 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 Jan 18 '10 at 06:22
  • In my experience if the attribute is missing nothing will be returned, no error will be thrown. – invertedSpear Jan 18 '10 at 14:58
  • 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 Jan 18 '10 at 15:27
1

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.

ocodo
  • 29,401
  • 18
  • 105
  • 117