XPath - 找到即将到来的生日

时间:2013-06-04 11:56:08

标签: xpath xpath-2.0

如果给出以下XML,我怎样才能在10天内找到即将到来的生日的联系人?

<contacts>
  <contact>
    <name>bob</name>
    <birthday>1978-05-06</birthday>
  </contact>
  <contact>
    <name>mary</name>
    <birthday>1955-06-06</birthday>
  </contact>
  <contact>
    <name>john</name>
    <birthday>1998-05-06</birthday>
  </contact>
</contacts>

我有以下xpath,但是因为month-from-dateTime返回一个整数(5)而不是'0'填充字符串(05),所以它会崩溃。有没有办法在Xpath中建立一个日期,它接受日,月,年的整数参数,而不是我的连接黑客串联字符串?

/contacts/contact[days-from-duration(xs:dateTime(concat(year-from-dateTime(current-date()),'-',month-from-dateTime(xs:dateTime(birthday)),'-',day-from-dateTime(xs:dateTime(birthday)))) - current-date()) < 10]

1 个答案:

答案 0 :(得分:1)

您可以使用yearMonthDuration添加足够的年数来将日期移至当前年份:

/contacts/contact[ 
  xs:dateTime(birthday) + xs:yearMonthDuration("P1Y") * (year-from-dateTime(current-date()) -  year-from-dateTime(xs:dateTime(birthday))) < current-date() + xs:dayTimeDuration("P10D")
]

要检查过去的生日是不是(为了让我们避免在这里输入两次,这样的作品):

/contacts/contact[ 
  for $thisYearBirthDay in xs:dateTime(birthday) + xs:yearMonthDuration("P1Y") * (year-from-dateTime(current-date()) -  year-from-dateTime(xs:dateTime(birthday)))  
  return $thisYearBirthDay >= current-date() and $thisYearBirthDay < current-date() + xs:dayTimeDuration("P10D")
]

但是,要实际使其正常工作,您需要检查当前和下一个年,以防当前日期在圣诞节左右,例如:

/contacts/contact[ 
  exists((for $delta in (0, 1) return xs:dateTime(birthday) + xs:yearMonthDuration("P1Y") * ($delta + year-from-dateTime(current-date()) -  year-from-dateTime(xs:dateTime(birthday))))[. >= current-date() and . < current-date() + xs:dayTimeDuration("P10D")])
]