这是一个有效的XPath表达式吗?

时间:2010-05-20 13:22:36

标签: xpath xml-libxml

此xpath是否为有效的XPath表达式? (它做它应该做的事。)

#!/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;
}

2 个答案:

答案 0 :(得分:8)

是的。这是一个有效的XPath表达式。

如果你把它写成:

,可能会有点简单
/result/cd[artists/artist[@class="2"]]/title

答案 1 :(得分:3)

是的,您可以在谓词中使用任何表达式,这意味着您可以嵌套它们。

参考