Hi, this is the content of my XML file:
<?xml version='1.0' encoding='ISO-8859-1'?> <mainNode> <sub time='08:00'> <status id='2'>On</status> <status id='3'>Off</status> </sub> <sub time='13:00'> <status id='4'>On</status> <status id='7'>On</status> </sub> <sub time='16:00'> <status id='5'>On</status> <status id='6'>On</status> <status id='7'>Off</status> <status id='8'>On</status> </sub> <sub time='20:00'> <status id='4'>Off</status> <status id='7'>On</status> </sub> <sub time='23:59'> <status id='4'>On</status> <status id='7'>On</status> </sub> </mainNode>
My program gets the current time: if I get 15.59, I must retrieve all the status id of the next sub time (16.00):
<sub time='16:00'> <status id='5'>On</status> <status id='6'>On</status> <status id='7'>Off</status> <status id='8'>On</status> </sub>
With a second XPath query I must get all the status id of the previous sub time (13.00). How to do it? I know SQL but I’m quite new to XPath. I accept urls to serious XPath resources too, if any. Thanks!
Here are two solutions:
I. XPath 1.0
This is one pair of XPath 1.0 expressions that select the required nodes:
selects the first
subnode with time later than15:59.selects selects the first
subnode with the previous than15:59subtime.We can include these in an XSLT transformation and check that the really wanted result is produced:
When the above transformation is applied on the originally provided XML document:
the wanted result is produced:
Do note the following:
The use of the XPath
translate()function to get rid of the colonsThe use of the
last()function in the second expressionThere is no need to convert the time to seconds before the comparison
When used as part of an XML document (such as an XSLT stylesheet, the
<operator must be escaped.II. XPath 2.0
In XPath 2.0 we can use the following two expressions to produce select the desired nodes:
selects the first
subnode with time later than15:59.selects selects the first
subnode with the previous than15:59subtime.We can include these in an XSLT 2.0 transformation and check that the really wanted result is produced:
When the above transformation is applied on the originally provided XML document (the same as in the first solution), the same wanted result is produced.
Do note the following:
xs:timeis a native data type. However, in order to construct anxs:time()from the values in the xml document, we have to concat to them the missing seconds part.xs:timevalues can be compared with the ‘atomic-value comarison operators‘ such asltorgt.