首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mojo获取attr名称

使用mojo获取attr名称
EN

Stack Overflow用户
提问于 2014-10-24 22:39:25
回答 2查看 165关注 0票数 1

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

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

我想知道有两个名为'a‘和'b’的属性。

EN

回答 2

Stack Overflow用户

发布于 2014-10-24 23:04:37

使用attr获取属性及其值:

代码语言:javascript
复制
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');

输出:

代码语言:javascript
复制
attributes: $VAR1 = {
  'b' => '2',
  'a' => '1'
};

attribute a has value 1
attribute b has value 2

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

票数 3
EN

Stack Overflow用户

发布于 2014-10-25 08:59:06

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

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

代码语言:javascript
复制
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>

输出:

代码语言:javascript
复制
Attributes: { a => 1, b => 2 }
   Content: Fourth
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26550201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档