tags:

views:

28

answers:

2

So given this XML...

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tree dah="false">
        <tree dah="false">
            <tree dah="false"/>
            <tree dah="false"/>
        </tree>
        <tree dah="false">
            <tree dah="true"/>
            <tree dah="false"/>
        </tree>
    </tree>
</root>

...I need an XPath that will evaluate to true since there is at least one tree/@dah='true'.

But that would evaluate to false if the XML looked like this...

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tree dah="false">
        <tree dah="false">
            <tree dah="false"/>
            <tree dah="false"/>
        </tree>
        <tree dah="false">
            <tree dah="false"/>
            <tree dah="false"/>
        </tree>
    </tree>
</root>

Also, the tree nodes may be any depth. I have three levels in my example, but it could go much deeper.

+1  A: 
/root//tree[@dah='true']
MooGoo
I don't want the node, but your solution works as /root//tree/@dah='true'. Thank you.
dacracot
//tree/@dah="true" or /root//tree/@dah="true" should get you just true or false.
Dunderklumpen
@dacracot, MooGoo's answer *will* evaluate to true/false as you requested. If `/root//tree[@dah = 'true']` selects an empty nodeset, that evaluates to false in a boolean context. A non-empty nodeset evaluates to true in a boolean context.
LarsH
+1  A: 

Use:

boolean(/root//tree[@dah='true'])

or

boolean((/root//tree[@dah='true'])[1])

Both expressions are equivalent, but the second would be more efficient with dumb (non-optimizing) XPath engines.

The result is true() if there exists a tree element in the XML document with a dah attribute with value 'true' -- otherwise the result is false().

Dimitre Novatchev
Why the "boolean()" function?
dacracot
Also, is the [1] to tell it to stop at the first occurrence?
dacracot
@dacracot [Why the boolean() fn.] Because you want `true`/`false` returned and this is exactly what the `boolean()` function does: http://www.w3.org/TR/1999/REC-xpath-19991116/#function-boolean
Dimitre Novatchev
@dacracot [Also, is the [1] to tell it to stop at the first occurrence?] Yes, most XPath engines have at least this intelligence, not to evaluate the expression further.
Dimitre Novatchev