Mojo :: DOM是否提供了使用嵌套语法的可能性?

sid*_*com 3 xml perl mojolicious

我怎么能用Mojo :: DOM模块编写这个例子?

#!/usr/bin/env perl
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;
}
Run Code Online (Sandbox Code Playgroud)

tem*_*ire 5

Mojo :: DOM支持CSS3选择器,它们很棒,但不如xpath那么通用; 下降到节点后,CSS3不提供提升的方法.

你可以完成同样的事情,虽然它涉及更多:

Mojo::DOM->new($string)
  ->find('result:root > cd > artists > artist.2')
  ->each(sub { say shift->parent->parent->title->text });
Run Code Online (Sandbox Code Playgroud)

要么

say $_->parent->parent->title->text
  for Mojo::DOM->new($string)
    ->find('result:root > cd > artists > artist.2')->each;
Run Code Online (Sandbox Code Playgroud)