Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid XPath expression?

Is this xpath a valid XPath expression? (It does what it should ).

#!/usr/bin/env perl
use strict; use warnings; use 5.012;
use XML::LibXML;

my $string =<<EOS;
<result>
    <cd>
    <artists>
        <artist class="1">Pumkinsingers</artist>
        <artist class="2">Max and Moritz</artist>
    </artists>
    <title>Hello, Hello</title>
    </cd>
    <cd>
    <artists>
        <artist class="3">Green Trees</artist>
        <artist class="4">The Leons</artist>
    </artists>
    <title>The Shield</title>
    </cd>
</result>
EOS
#/
my $parser = XML::LibXML->new();
my $doc = $parser->load_xml( string => $string );
my $root = $doc->documentElement;

my $xpath = '/result/cd[artists[artist[@class="2"]]]/title';

my @nodes = $root->findnodes( $xpath );
for my $node ( @nodes ) {
    say $node->textContent;
}
like image 656
sid_com Avatar asked Dec 22 '22 03:12

sid_com


2 Answers

Yep. That's a valid XPath expression.

It could be a little simplier if you wrote it as:

/result/cd[artists/artist[@class="2"]]/title
like image 59
Jon W Avatar answered Jan 01 '23 09:01

Jon W


Yes, you can use any expression inside a predicate, which means you can nest them.

References

  • w3c.org/XPath 2.0 specification
    • Basics - "In general, the operands of an expression are other expressions. XPath allows expressions to be nested with full generality"
    • Predicates - Predicate ::= "[" Expr "]"
  • xml.com Top Ten Tips to Using XPath and XPointer
    • "Keep an open mind about predicates: nested, 'compound,' and so on."
like image 41
polygenelubricants Avatar answered Jan 01 '23 11:01

polygenelubricants