Perl 使用mojo获取attr名称

Perl 使用mojo获取attr名称,perl,mojolicious,Perl,Mojolicious,使用Mojo,如何获取属性的名称?例如: 我想知道有两个名为“a”和“b”的属性。使用attr获取属性及其值: my $dom = Mojo::DOM->new('<test a="1" b="2">hello</test>'); my $t = $dom->at('test'); # save the attributes in a hash: my $attr_h = $t->attr; say "attributes: " . Dumper($

使用Mojo,如何获取属性的名称?例如:


我想知道有两个名为“a”和“b”的属性。

使用
attr
获取属性及其值:

my $dom = Mojo::DOM->new('<test a="1" b="2">hello</test>');
my $t = $dom->at('test');

# save the attributes in a hash:
my $attr_h = $t->attr;
say "attributes: " . Dumper($attr_h);

# get the values for 'a' and 'b'
say "attribute a has value " . $t->attr('a');
say "attribute b has value " . $t->attr('b');

显然,您可以使用散列键来获取属性数组。

要获取节点的属性,请使用

另外请注意,可以使用以下命令搜索具有特定属性值的节点:

attributes: $VAR1 = {
  'b' => '2',
  'a' => '1'
};

attribute a has value 1
attribute b has value 2
use strict;
use warnings;

use Data::Dump qw(dump);
use Mojo::DOM;

my $dom = Mojo::DOM->new( do { local $/; <DATA> } );

for my $test ( $dom->find('test[a=1][b=2]')->each ) {
    print "Attributes: ", dump($test->attr), "\n";
    print "   Content: ", $test->content, "\n";
}

__DATA__
<html>
<body>
    <test a="no" b="no">First</test>
    <test a="no" b="2">Second</test>
    <test a="1" b="no">Third</test>
    <test a="1" b="2">Fourth</test>
</body>
</html>
Attributes: { a => 1, b => 2 }
   Content: Fourth