4

这个 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;
}
4

2 回答 2

8

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

如果你把它写成这样可能会更简单一点:

/result/cd[artists/artist[@class="2"]]/title
于 2010-05-20T13:24:10.397 回答
3

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

参考

于 2010-05-20T13:33:57.607 回答