Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: language selection via libxml

by choroba (Cardinal)
on Jan 20, 2014 at 12:29 UTC ( [id://1071305]=note: print w/replies, xml ) Need Help??


in reply to Re^2: language selection via libxml
in thread language selection via libxml

Not really. String literals must be enclosed in quotes in XPath expressions, and XPath does not know Perl variables (unless you use XML::XSH2).
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^4: language selection via libxml
by tangent (Parson) on Jan 20, 2014 at 12:41 UTC
    With the quotes I get
    Scalar found where operator expected near ""/language/$language/widget +[\@ID="$id" String found where operator expected near "$id"]"" syntax error near ""/language/$language/widget[\@ID="$id"
    Update: Perhaps I should have said "lose double quotes around $id", though no quotes works for me too:
    "/language/$language/widget[\@ID="$id"]" - Error "/language/$language/widget[\@ID='$id']" - OK "/language/$language/widget[\@ID=$id]" - OK
      "/language/$language/widget[\@ID=$id]" - OK
      Well, it is a valid syntax, but the meaning is different: it tries to find a widget whose ID attribute has the same value as the text of the child of widget whose name is $id. Barewords are not promoted to strings in XPath.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        I am trying to get this as I believe Xpath expressions to be very powerful and I've always had a hard time understanding them.

        The two examples marked OK above seem to behave the same way:

        use XML::LibXML; my $tree = XML::LibXML->load_xml(string => <<'EOT'); <?xml version="1.0"?> <language> <english> <widget ID="1">input</widget> <widget ID="2">output</widget> </english> <deutsch> <widget ID="1">eingabe</widget> <widget ID="2">ausgabe</widget> </deutsch> </language> EOT test('english',1); test('deutsch',1); sub test { my ($language,$id) = @_; my @result=$tree->findnodes("/language/$language/widget[\@ID=$id]" +); print $_->textContent . "\n" for @result; my @result2=$tree->findnodes("/language/$language/widget[\@ID='$id +']"); print $_->textContent . "\n" for @result2; }
        Output:
        input input eingabe eingabe

      You need to escape the quotes as well or use single quotes around your string:

      $result=$tree->findnodes('/language/$language/widget[@ID="$id"]');
        Using your example I get:
        XPath error : Invalid expression /language/$language/widget[@ID="$id"] ^

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1071305]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-24 23:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found