【问题标题】:parsing with Mojo::DOM使用 Mojo::DOM 解析
【发布时间】:2012-10-28 18:21:27
【问题描述】:

我正在使用Mojo::UserAgent->new 获取一些具有以下格式的 XML:

<row>
<td> content1 </td>
<td> content2 </td>
<td> content3 </td>
</row>
<row>
<td> content4 </td>
<td> content5 </td>
<td> content6 </td>
</row>

是否可以这样查看结果:

content1,content2,content3
content4,content5,content6

下面是我正在使用的查询,它得到不同的结果

 $ua->get($url)->res->dom->at->(row)->children->each(sub {print "$_\t"})

【问题讨论】:

  • 请务必发布真实代码。您发布的行甚至没有编译。请参阅我的 answer,了解为什么使用 at 对您不起作用。
  • 喂?你还活着吗? ;)

标签: perl mojolicious mojo


【解决方案1】:

当然,Mojo::Collection 在幕后工作是绝对可能的,而且并不难。

代码

# replace this line by your existing $ua->get($url)->res->dom code
my $dom = Mojo::DOM->new(do { local $/ = undef; <DATA> });

# pretty-print rows
$dom->find('row')->each(sub {
    my $row = shift;
    say $row->children->pluck('text')->join(', ');
});

数据

__DATA__
<row>
<td> content1 </td>
<td> content2 </td>
<td> content3 </td>
</row>
<row>
<td> content4 </td>
<td> content5 </td>
<td> content6 </td>
</row>

输出

content1, content2, content3
content4, content5, content6

一些cmets

  • each 评估集合中每个元素的代码引用(这是 find 返回的内容)。
  • pluck 返回一个 Mojo::Collection 对象,该对象具有给定方法名称的返回值(在本例中为text)。这只是map简单东西的一种奇特方式。
  • text 自动修剪元素内容。
  • join 将 Mojo::Collection 对象的所有元素连接在一起,在本例中为 row 的所有 td 元素。
  • 您的代码甚至无法编译,但使用 at 无论如何都不会工作,因为它只返回第一个匹配的 DOM 元素,而不是全部。您想要迭代所有行。

HTH!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 2017-04-30
    • 2017-04-29
    • 1970-01-01
    • 2017-09-04
    • 2013-02-15
    • 2018-03-30
    • 2013-03-18
    相关资源
    最近更新 更多