【发布时间】:2018-05-16 23:39:07
【问题描述】:
我有点卡在从简单的结构化 XML 中获取 Qty 的最大值。所以需要一些帮助!
我的 XML 如下:
<?xml version="1.0" encoding="utf-8"?>
<TANK_DETAILS>
<TABLES>
<OUTPUT>
<item>
<AREA>INDIA</AREA>
<MACHINE>T100</MACHINE>
<MATERIAL>1111111</MATERIAL>
<BATCH>100</BATCH>
<QTY>18815.000</QTY>
</item>
<item>
<AREA>INDIA</AREA>
<MACHINE>T102</MACHINE>
<MATERIAL>1111111</MATERIAL>
<BATCH>200</BATCH>
<QTY>100.000</QTY>
</item>
<item>
<AREA>INDIA</AREA>
<MACHINE>T103</MACHINE>
<MATERIAL>1111111</MATERIAL>
<BATCH>300</BATCH>
<QTY>10000.000</QTY>
</item>
<item>
<AREA>INDIA</AREA>
<MACHINE>T101</MACHINE>
<MATERIAL>1111111</MATERIAL>
<BATCH>400</BATCH>
<QTY>35550.000</QTY>
</item>
<item>
<AREA>INDIA</AREA>
<MACHINE>T104</MACHINE>
<MATERIAL>1111111</MATERIAL>
<BATCH>500</BATCH>
<QTY>10100.000</QTY>
</item>
</OUTPUT>
</TABLES>
</TANK_DETAILS>
我想得到<MACHINE>,<BATCH> & <Qty> 其中<QTY> 是最大值。
输出 XML 应如下所示:
<Rowsets>
<Rowset>
<Row>
<MACHINE>T101</MACHINE>
<BATCH>400</BATCH>
<QTY>35550.000</QTY>
</Row>
</Rowset>
</Rowsets>
我正在尝试的 XSLT 如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes" method="xml" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<!-- Putting the maximum QTY from the list into a variable -->
<xsl:variable name="max-QTY">
<xsl:call-template name="find-max">
<!-- Select the list of QTY elements -->
<xsl:with-param name="QTY" select="//*[contains(local-name(), 'QTY')]"/>
</xsl:call-template>
</xsl:variable>
<xsl:template match="*">
<!-- Displaying the result -->
<QTY>
<xsl:value-of select="$max-QTY"/>
</QTY>
</xsl:template>
<!-- This template works recursively on the list of QTY. -->
<xsl:template name="find-max">
<xsl:param name="QTY"/>
<!-- The value of the first QTY in this list. -->
<xsl:variable name="this-QTY">
<xsl:value-of select="$QTY[position() = 1]"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$QTY">
<!-- The maximum value of the remaining QTY in this list. -->
<xsl:variable name="other-QTY">
<xsl:call-template name="find-max">
<xsl:with-param name="QTY" select="$QTY[position() != 1]"/>
</xsl:call-template>
</xsl:variable>
<!-- Return the maximum of this QTYand the remaining QTY. -->
<xsl:choose>
<xsl:when test="$other-QTY> $this-QTY">
<xsl:value-of select="$other-QTY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$this-QTY"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<!-- We've reached the last QTY in the list. -->
<xsl:otherwise/>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
我得到的输出是:
<?xml version="1.0" encoding="utf-8"?>
<QTY>35550.000</QTY>
所以我能够找到最大 <QTY>,但我正在努力为最大 <QTY> 获得相应的 <MACHINE> & <BATCH>。
我确定我犯了一个小错误,但我非常卡住并面临编码人员的障碍。
另外,如果有更好的方法来找到 max ,请提供最佳答案。那会很有帮助。
谢谢。
【问题讨论】:
标签: xml xslt xslt-1.0 xslt-2.0