Home > Blockchain >  How do I use XPath 3.0 to find the latest date of each non-unique ID?
How do I use XPath 3.0 to find the latest date of each non-unique ID?

Time:02-24

First time I'm posting here myself instead of searching for existing answers. Wanted to try it out in case my demand for more specific questions increases.

So I want to write an XPath 3.0 query to extract all the names from each <Flow>, but if there is multiple <Flow> with the same ID, I only want to return the name of the one with the more recent date, <Published>.

My XML looks like this:

<Flows>
    <Flow>
        <ID>172</ID>
        <Name>Name 1 version 1</Name>
        <Published>2021-09-30</Published>
    </Flow>
    <Flow>
        <ID>172</ID>
        <Name>Name 1 version 2</Name>
        <Published>2022-01-15</Published>
    </Flow>
    <Flow>
        <ID>287</ID>
        <Name>Name 2 version 1</Name>
        <Published>2022-01-14</Published>
    </Flow>
    <Flow>
        <ID>9</ID>
        <Name>Name 3 version 1</Name>
        <Published>2021-10-15</Published>
    </Flow>
</Flows>

And I want the following output:

<Name>Name 1 version 2</Name>
<Name>Name 2 version 1</Name>
<Name>Name 3 version 1</Name>

CodePudding user response:

this would return all the names, where the date equals the max for a given ID

let $maxDate := function($flows as element(Flows),$id as xs:integer) as xs:date {
    max($flows/Flow[ID = $id]/Published/xs:date(.)) 
 }
return //Flow[Published/xs:date(.) eq $maxDate(/Flows,./ID/.)]/Name

note, that in case there are multiple Flow elements with the same ID, and the max date, it would return all of them

  • Related