使用mojo获取attr名称

时间:2014-10-24 14:39:25

标签: perl mojolicious

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

<test a="1" b="2">

我想知道有两个名为&#39; a&#39;和&#39; b&#39;。

2 个答案:

答案 0 :(得分:3)

使用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

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

答案 1 :(得分:0)

要获取节点的属性,请使用Mojo::DOM->attr

另请注意,您可以使用css selectors搜索具有特定属性值的节点:

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