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

标签 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;
}

最佳答案

Mojo::DOM 支持 CSS3 选择器,这很了不起,但不如 xpath 通用; CSS3 不提供在下降到节点后上升的方法。

您可以完成同样的事情,尽管涉及更多:

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

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

关于xml - Mojo::DOM 是否提供使用嵌套语法的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8588542/

相关文章:

c# - 反序列化 XmlDocument 的最短方法

javascript - 从 mojolicious 调用 javascript href

perl - Mojolicious 模板的测试覆盖率

perl - 如何在 Mojolicious 的 Web 请求之外呈现模板?

perl - 如何使用 MooseX::Method::Signatures 获取传递给方法的所有参数?

perl - 为自记录代码初始化 "undef"?

javascript - Blogger 搜索标签条件语句

java - 如何将xml转换为java字符串列表

c++ - 使用 P/Invoke 从 MFC DLL 函数读取 VB.NET 中的结构化数据

perl - 如何使用 Perl 创建 CSV 文件?