mush4brains has asked for the wisdom of the Perl Monks concerning the following question:

Maybe my brain's unusually mushy today, but darned if I can figure out how to use variables in XPath expressions with XML::XPath.
I'd like to do something like...
@nodes = $xp->findnodes("//A[$save = @idref]//B[@id = $save]");
...where a variable $save captures the value of each A's idref attr and finds descendant B's with id attr of that value.
I've perused XML::XPath documentation, looked at XML::XPath::Variable, and yet the answer eludes me.
Thanks for any (merciful) assistance.
Mush

Replies are listed 'Best First'.
Re: XML::XPath and variables
by Zaxo (Archbishop) on Sep 13, 2002 at 15:42 UTC

    You need to escape the the @'s where they are in XPath symbols. Perl is trying to interpolate arrays there and coming up empty.

    @nodes = $xp->findnodes( "//A[$save = \@idref]//B[\@id = $save]" );

    After Compline,
    Zaxo

Re: XML::XPath and variables
by mirod (Canon) on Sep 13, 2002 at 16:31 UTC

    Isn't it fun to mix Perl punctuation with XPath? My take would be that you are missing the quotes around $save. Plus as mentionned previously you should backslash your @'s

    In such a case I use qq{} to create the string instead of the usual quotes, it gets a little clearer:

    @nodes = $xp->findnodes( qq{//A["$save" = \@idref]//B[\@id = "$save"]} +);
      As I look back on this, my question was confused on many levels. (grin)

      In my actual code, I'm using single quotes around the XPath expr, so the @s and $s aren't an issue. (Shame on me for misstating.)

      Also, I think I'm missing something about variables in XPath. For example, there is actually no "assignment" operator in the XPath 1.0 spec, so assigning to a variable like this isn't really possible. In the context of XSLT, XPath has "variables", but again, no assignment within the XPath expression.

      And I guess I'm confused as to how XML::XPath::Variable is used...

      Or maybe I simply have no idea what I'm talking about (quite likely ;-).

      - Mush

        matts could explain it better, but I believe XPath variables are only included in the module for completedness sake. They are of no use outside of an XSLT context.

        So your brain isn't that mushy. ;--)