for loop as predicate xquery, xpath

161 Views Asked by At

I have a list of /bibl entries, each with a /date @when="YEAR" child element. I am trying to output only the first instance of each year.

`<listBibl>
            <bibl>
                <date when="1746"/> 
            </bibl>
            <bibl>
                <date when="1746"/> 
            </bibl>
            <bibl>
                <date when="1746"/> 
            </bibl>
            <bibl>
                <date when="1746"/>
            </bibl>
          <bibl>
                <date when="1747"/> 
            </bibl>
            <bibl>
                <date when="1747"/>
            </bibl>
            <bibl>
                <date when="1747"/> 
            </bibl>
          <bibl>
                <date when="1754"/>
            </bibl>
            <bibl>
                <date when="1754"/>
            </bibl>
          </listBibl>

I have written an expression that finds this: for $d in /date/@when return (/date[@when=$d])[1] But this won’t work in the programme (teipublisher) I am using to output the attribute value. Does anybody have any suggestions about how I might do this differently.

1

There are 1 best solutions below

0
On BEST ANSWER

By using BaseX, v.9.6.4

XQuery

xquery version "3.1";

declare context item := document {
<listBibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1754"/>
    </bibl>
    <bibl>
        <date when="1754"/>
    </bibl>
</listBibl>
};

<listBibl>
{
  for $x in ./listBibl/bibl
  let $date := $x/date/@when
  group by $date
  order by $date
  return <bibl>
        <date when="{$date}"/>
    </bibl>
}
</listBibl>

Output XML

<listBibl>
  <bibl>
    <date when="1746"/>
  </bibl>
  <bibl>
    <date when="1747"/>
  </bibl>
  <bibl>
    <date when="1754"/>
  </bibl>
</listBibl>