是否有理由在我的 XML::LibXML-example 中使用 XML::LibXML::Number-object?

发布于 2024-09-01 23:05:02 字数 1023 浏览 2 评论 0原文

在这个例子中,我得到了时间“96”。是否有可能需要 XML::LibXML-Number-object 来实现目标?

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use XML::LibXML;

my $xml_string =<<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<filesystem>
   <path>
     <dirname>/var</dirname>
     <files>
       <action>delete</action>
       <age units="hours">10</age>
     </files>
     <files>
       <action>delete</action>
       <age units="hours">96</age>
     </files>
   </path>
</filesystem>
EOF
#/

my $doc = XML::LibXML->load_xml( string => $xml_string );
my $root = $doc->documentElement;

my $result = $root->find( '//files/age[@units="hours"]' );
$result = $result->get_node( 1 );
say ref $result; # XML::LibXML::Element
say $result->textContent; # 96

$result =  $root->find ( 'number( //files/age[@units="hours"] )' );
say ref $result; # XML::LibXML::Number
say $result; # 96

In this example I get to times '96'. Is there a possible case where I would need a XML::LibXML-Number-object to to achieve the goal?

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use XML::LibXML;

my $xml_string =<<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<filesystem>
   <path>
     <dirname>/var</dirname>
     <files>
       <action>delete</action>
       <age units="hours">10</age>
     </files>
     <files>
       <action>delete</action>
       <age units="hours">96</age>
     </files>
   </path>
</filesystem>
EOF
#/

my $doc = XML::LibXML->load_xml( string => $xml_string );
my $root = $doc->documentElement;

my $result = $root->find( '//files/age[@units="hours"]' );
$result = $result->get_node( 1 );
say ref $result; # XML::LibXML::Element
say $result->textContent; # 96

$result =  $root->find ( 'number( //files/age[@units="hours"] )' );
say ref $result; # XML::LibXML::Number
say $result; # 96

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留一抹残留的笑 2024-09-08 23:05:02

尽管我经常使用 XML::LibXML,但我从未遇到过 XML::LibXML::Number 类。它的存在似乎是为了允许 XPath 表达式对节点的文本内容进行数值断言(例如:> 10)。

如果您想要的只是数字“96”,那么最简单的方法可能是:

my $result = $root->findvalue( '//files/age[@units="hours"]' );

我发现对于获取多个值有用的习惯用法是:

my @values = map { $_->to_literal } $doc->find('//files/age');

Although I've used XML::LibXML quite a bit I have never encountered the XML::LibXML::Number class. It seems to exist to allow XPath expressions to make numerical assertions about the text content of a node (e.g.: > 10).

If all you want is the number '96' then the easiest way is probably:

my $result = $root->findvalue( '//files/age[@units="hours"]' );

An idiom I find useful for getting multiple values is:

my @values = map { $_->to_literal } $doc->find('//files/age');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文