加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl Xpath:日期年份之前的搜索项目

发布时间:2020-12-15 21:57:29 所属栏目:大数据 来源:网络整理
导读:我有一个包含电影的xml数据库,例如: film id="5" titleThe Avengers/title date2012-09-24/date familyComics/family/film 从Perl脚本我想按日期找到电影. 如果我搜索一个特殊年份的电影,例如: my $query = "//collection/film[date = 2012]"; 它完全正常
我有一个包含电影的xml数据库,例如:
<film id="5">
        <title>The Avengers</title>
        <date>2012-09-24</date>
        <family>Comics</family>
</film>

从Perl脚本我想按日期找到电影.
如果我搜索一个特殊年份的电影,例如:

my $query = "//collection/film[date = 2012]";

它完全正常工作,并返回2012年的所有电影,但如果我在一年之前搜索所有电影,它就不起作用,例如:

my $query = "//collection/film[date < 2012]";

它返回所有电影..

解决方法

好吧,像往常一样,有不止一种方法可以做到这一点. )要么让XPath工具知道它应该比较日期(它从一开始就不知道)与这样的事情:
my $query = '//collection/film[xs:date(./date) < xs:date("2012-01-01")]';

…或者你只是咬紧牙关,只是比较’yyyy’子串:

my $query = '//collection/film[substring(date,1,4) < "2012"]';

我认为前者在语义上更好,但需要一个支持XPath 2.0的高级XML解析器工具.后者使用XML :: XPath成功验证.

更新:我想解释为什么你的第一个查询有效. )看,你不比较那里的日期 – 你比较数字,但只是因为’=’运算符.引自the doc:

When neither object to be compared is a node-set and the operator is =
or !=,then the objects are compared by converting them to a common
type as follows and then comparing them. If at least one object to be
compared is a boolean,then each object to be compared is converted to
a boolean as if by applying the boolean function. Otherwise,if at
least one object to be compared is a number,then each object to be
compared is converted to a number as if by applying the number
function.

看到?您的’2012-09-24’已转换为数字 – 并成为2012年.当然,这相当于2012年.)

但这不适用于任何其他比较运算符:这就是为什么你需要使用substring,或者将date-string转换为数字.我认为第一种方法可能更具可读性 – 也许更快. )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读