xml - How to select nodes with conditions based on attributes -


i want use xpath in xslt select nodes conditions based on attribute values.

to illustrate question, have short example xml instance below:

<?xml version="1.0" encoding="utf-8"?> <root>     <elementa fid="2013_4_20150722_0" datetime="2015-07-13t01:04:20+02:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-13t01:04:20+02:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-20t14:14:22+02:00"/> </root> 

and want select elementa nodes following conditions:

  • the attribute fid unique
  • if there multiple elementa nodes same fid attribute value, 1 newest datetime selected.

so in example want select first , third elementa.

how can achieve xpath 2.0 in xslt 2.0?

here pure, single , efficient (no sorting) xpath 2.0 expression, selects wanted elements:

 $fid in distinct-values(/*/*/@fid),      $maxtime in  max(/*/*[@fid eq $fid]/@datetime/xs:datetime(.))    return      (/*/*[@fid eq $fid , xs:datetime(@datetime) eq $maxtime])[1] 

here proof, in xslt used copy result of evaluating expression output:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"   xmlns:xs="http://www.w3.org/2001/xmlschema">  <xsl:output omit-xml-declaration="yes" indent="yes"/>    <xsl:template match="/">     <xsl:sequence select=      "for $fid in distinct-values(/*/*/@fid),           $maxtime in  max(/*/*[@fid eq $fid]/@datetime/xs:datetime(.))         return           (/*/*[@fid eq $fid , xs:datetime(@datetime) eq $maxtime])[1]             "/>   </xsl:template> </xsl:stylesheet> 

when above transformation applied on source xml document:

<root>     <elementa fid="2013_4_20150722_0" datetime="2015-07-13t01:04:20+02:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-13t01:04:20+02:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-20t12:14:22+00:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-20t14:14:22+02:00"/>     <elementa fid="2013_4_20150721_0" datetime="2015-07-20t14:14:22+02:00"/> </root> 

the wanted, correct result produced:

<elementa fid="2013_4_20150722_0" datetime="2015-07-13t01:04:20+02:00"/> <elementa fid="2013_4_20150721_0" datetime="2015-07-20t12:14:22+00:00"/> 

note on efficiency:

this xpath expression uses max() function,

o(n)

-- better o(n*log(n)) of solution uses sorting.


Comments

  1. Blackjack Review 2021 - Casino Sites
    You will also see the bonuses 포커 게임 다운 and promotions offered 22 bet by 포커 족보 순위 the casino online. If you are having issues or a need 야구분석 to place your bets on this 네임드사다리 page,

    ReplyDelete

Post a Comment

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -