XSLT 排序孙节点并选择另一个孙节点的值 [英] XSLT Sort grandchild nodes and pick the value of another grandchild
本文介绍了XSLT 排序孙节点并选择另一个孙节点的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找出以下 XML 的 XSLT(CSV 输出).
我想对孙节点进行排序,即对 Month 节点进行排序,然后选择具有最高月份值的集合的 Sales_Program-ID 节点值.
I am trying to figure out the XSLT (CSV output) for the below XML.
I would like to sort the grandchildren nodes i.e. sort Month node and pick the Sales_Program-ID node value of the set with the highest month value.
XML
<Root>
<Level1>
<EMPLID>123</EMPLID>
<Program>
<Sales_Program Name="XYZ">
<ID1>ab</ID1>
</Sales_Program>
<Start_Date>Jan1st</Start_Date>
**<Month>1</Month>**
</Program>
<Program>
<Sales_Program Name="ABC">
<ID1>cd</ID1>
</Sales_Program>
<Start_Date>Feb1</Start_Date>
**<Month>2</Month>**
</Program>
</Level1>
<Level1>
<EMPLID>456</EMPLID>
<Program>
<Sales_Program Name="XYZ">
<ID1>ab</ID1>
</Sales_Program>
<Start_Date>Jan1st</Start_Date>
<Month>1</Month>
</Program>
</Level1>
</Root>
预期输出:
123,ab,Feb1,2 - (From first Level1 Node)
456,cd,Jan1st,1 (From second Level1 Node)
推荐答案
所以您想在 XSLT 3 中按 Month
子元素对 Program
元素进行排序,并支持您可以使用高阶 sort
函数
So you want to sort the Program
elements by the Month
child, in XSLT 3 with support for the higher-order sort
function you can do that with
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math"
exclude-result-prefixes="xs math"
version="3.0">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:apply-templates select="Root/Level1"/>
</xsl:template>
<xsl:template match="Level1">
<xsl:value-of select="EMPLID, sort(Program, (), function($p) { -$p/Month/xs:integer(.) })[1]/(Sales_Program/ID1, Start_Date, Month)" separator=","/>
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>
在 XSLT 2 中,您需要使用 xsl:perform-sort
在您自己的函数中实现排序:
in XSLT 2 you need to implement the sorting in your own function with xsl:perform-sort
:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:mf="http://example.com/mf"
exclude-result-prefixes="xs mf"
version="2.0">
<xsl:output method="text"/>
<xsl:function name="mf:sort">
<xsl:param name="programs" as="element(Program)*"/>
<xsl:perform-sort select="$programs">
<xsl:sort select="xs:integer(Month)" order="descending"/>
</xsl:perform-sort>
</xsl:function>
<xsl:template match="/">
<xsl:apply-templates select="Root/Level1"/>
</xsl:template>
<xsl:template match="Level1">
<xsl:value-of select="EMPLID, mf:sort(Program)[1]/(Sales_Program/ID1, Start_Date, Month)" separator=","/>
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>
这篇关于XSLT 排序孙节点并选择另一个孙节点的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文