我正在尝试检索第一个唯一的 2 个属性集。
我正在寻找每个学生的名字及其第一个独特的组。如果某个学生的第一组已被任何学生占用,则应列出下一个独特的组。我已经发布了我的 XML 和预期结果 XML。
我需要 XSLT 语句才能获得此结果(版本 1.0)。谢谢。
这是我的 xml 结构
<Socrates>
<Student name='Aristotle' group='1' />
<Student name='Aristotle' group='2' />
<Student name='Aristotle' group='3' />
<Student name='Aristotle' group='4' />
<Student name='Plato' group='1' />
<Student name='Plato' group='2' />
<Student name='Plato' group='3' />
<Student name='Xenophon' group='4' />
<Student name='Xenophon' group='5' />
<Student name='Xenophon' group='6' />
<Student name='Critias' group='1' />
<Student name='Critias' group='2' />
<Student name='Critias' group='3' />
<Student name='Critias' group='4' />
<Student name='Critias' group='5' />
<Student name='Critias' group='6' />
</Socrates>
结果 XML
<Socrates>
<Student name='Aristotle' group='1' />
<Student name='Plato' group='2' />
<Student name='Xenophon' group='4' />
<Student name='Critias' group='3' />
</Socrates>
最佳答案
另一种稍有不同的方法(尽管不一定是更好的方法)是将一个参数传递给每个 student 匹配项,其中包含以逗号分隔的 group 属性,这些属性已经已输出。每次匹配一个学生时,都会检查他们的组是否在他的参数中,如果没有则输出该学生,并获取下一个学生,并将当前组附加到参数中。
这是 XSLT,我对其进行了评论,以尝试更好地解释事情
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="Socrates">
<Socrates>
<xsl:apply-templates select="Student[1]"/>
</Socrates>
</xsl:template>
<xsl:template match="Student">
<!-- Parameter containin comma-delimited list of currently output groups -->
<xsl:param name="groupList" select="','" />
<xsl:choose>
<!-- Has the group already been output? -->
<xsl:when test="contains($groupList, concat(',', @group, ','))">
<!-- If so, move on to next student record -->
<xsl:apply-templates select="following-sibling::Student[1]">
<xsl:with-param name="groupList" select="$groupList" />
</xsl:apply-templates>
</xsl:when>
<!-- Group has not already been output -->
<xsl:otherwise>
<!-- Output the record -->
<xsl:copy-of select="." />
<!-- Get the next student with a different name -->
<xsl:apply-templates select="following-sibling::Student[@name!=current()/@name][1]">
<xsl:with-param name="groupList" select="concat($groupList, @group, ',')" />
</xsl:apply-templates>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
当应用于示例 XML 时,输出如下
<Socrates>
<Student name="Aristotle" group="1" />
<Student name="Plato" group="2" />
<Student name="Xenophon" group="4" />
<Student name="Critias" group="3" />
</Socrates>
请注意,这确实假设 student 元素始终按输入 XML 中的名称排序。
关于xml - XSLT 检索第一个唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792382/