具有条件的前一个兄弟的 XSLT 位置

XSLT position of preceeding sibling with a condition

我需要了解如何在使用 XSL 选择的子元素中获取具有相似值的平行元素的位置。我列出了带有特定参考的项目行作为子元素,然后我有子项目行,应该根据子元素值将其链接到项目行中。子项行应指示具有相似引用的项行的位置

我在括号 [ ] 中尝试了几种不同的前提方法,但到目前为止都没有成功。我只能使用 xslt 1.0

我有 xml 结构如下:

<goods>
    <item>
        <ref>a</ref>
    </item>
    <item>
        <ref>b</ref>
    </item>
    <item>
        <ref>c</ref>
    </item>
    <item>
        <ref>d</ref>
    </item>
    <subitem>
        <subref>c</subref>
    </subitem>
    <subitem>
        <subref>a</subref>
    </subitem>
</goods>

和我的 xsl (1.0) :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
    <xsl:template match="/">
        <xsl:call-template name="Line"/>
    </xsl:template>
    <xsl:template name="Line">
        <xsl:for-each select="goods/item">
            <xsl:value-of select="position()"/>
            <xsl:text>;</xsl:text>
            <xsl:value-of select="ref"/>
            <xsl:text>&#xD;</xsl:text>
        </xsl:for-each>
        <xsl:for-each select="goods/subitem">
            <xsl:text>0;</xsl:text>
            <xsl:value-of select="subref"/>
            <xsl:text>;</xsl:text>
            here would be some kind of conditional preceeding select needed
            <xsl:text>&#xD;</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

所需的输出为:

1;a
2;b
3;c
4;d
0;c;3
0;a;1

最后两行是子项目,最后一个数字应该告诉我项目元素的位置,相同的引用在哪里。在示例中,引用 'c' 位于位置为 3 的项目元素内部(第三个项目元素在子元素 'ref' 中具有 'c'),因此具有子引用值 'c' 的子项目应链接到示例中的项目位置 3。

每个子项目行也是如此:所有带有 subitem/subref = a 的位置都应为 1,所有带有 'b' 的位置为 2 等

这是您可以查看的一种方式:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:key name="item" match="item" use="ref" />

<xsl:template match="/goods">
    <xsl:for-each select="item">
        <xsl:value-of select="position()" />
        <xsl:text>;</xsl:text>
        <xsl:value-of select="ref"/>
        <xsl:text>&#xD;</xsl:text>
    </xsl:for-each>
    <xsl:for-each select="subitem">
        <xsl:text>0;</xsl:text>
        <xsl:value-of select="subref"/>
        <xsl:text>;</xsl:text>
        <xsl:value-of select="count(key('item', subref)/preceding-sibling::item) +1" />
        <xsl:text>&#xD;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

请注意,这假设每个 subref 都有对应的 item 和匹配的 ref 值。