You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从XML中按日期筛选每个唯一用户的最新记录?

需求:从XML数据中筛选每个员工的最新日期记录

需要从给定的XML数据里,为每个唯一的Employee筛选出对应日期最新的记录。

示例XML

<ReconciliationList>
  <ReconciliationListRow>
     <Employee>John Smith</Employee>
     <Date>2000-01-24</Date>
  </ReconciliationListRow>
  <ReconciliationListRow>
     <Employee>Marilyn Manson</Employee>
     <Date>2001-12-15</Date>
  </ReconciliationListRow>
  <ReconciliationListRow>
      <Employee>John Smith</Employee>
      <Date>2002-09-24</Date>
  </ReconciliationListRow>
  <ReconciliationListRow>
      <Employee>John Smith</Employee>
      <Date>1998-07-02</Date>
  </ReconciliationListRow>
  <ReconciliationListRow>
      <Employee>Liam Peters</Employee>
      <Date>1979-10-22</Date>
  </ReconciliationListRow>
</ReconciliationList>

期望输出

ReconciliationList:
2002-09-24   John Smith
2001-12-15   Marilyn Manson
1979-10-22   Liam Peters

现有XSLT模板代码

<xsl:template name="print">
  <xsl:for-each select="//ReconciliationList/ReconciliationListRow">
    <xsl:sort select="@DateStart" order="ascending"/>
    <tr>
      <xsl:call-template name="printresult">
        <xsl:with-param name="recrow" select="current()"/>
      </xsl:call-template>
    </tr>
  </xsl:for-each>
</xsl:template>

优化后的XSLT代码

首先在XSLT根节点下添加分组键定义,再修改print模板:

<!-- 定义按Employee分组的键 -->
<xsl:key name="employeeKey" match="ReconciliationListRow" use="Employee"/>

<xsl:template name="print">
  <!-- 输出标题 -->
  <text>ReconciliationList:&#10;</text>
  
  <!-- 遍历每个唯一的Employee分组 -->
  <xsl:for-each select="//ReconciliationList/ReconciliationListRow[generate-id() = generate-id(key('employeeKey', Employee)[1])]">
    <!-- 对当前员工的所有记录按日期降序排序 -->
    <xsl:for-each select="key('employeeKey', Employee)">
      <xsl:sort select="Date" order="descending"/>
      
      <!-- 仅输出每组的第一条(日期最新的记录) -->
      <xsl:if test="position() = 1">
        <text><xsl:value-of select="Date"/>   <xsl:value-of select="Employee"/>&#10;</text>
      </xsl:if>
    </xsl:for-each>
  </xsl:for-each>
</xsl:template>

优化说明

  1. 分组去重:使用Muenchian分组(兼容XSLT 1.0),通过employeeKey将相同Employee的记录归为一组,确保只处理每个员工的分组一次。
  2. 筛选最新记录:在每个员工分组内,按Date降序排序,取排序后的第一条记录,即为该员工的最新日期记录。
  3. 精简输出:直接输出纯文本格式,去掉原代码中多余的HTML<tr>标签,匹配期望的输出样式。

内容的提问来源于stack exchange,提问作者Black_mamba___

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 14:10:25