简体   繁体   中英

XSLT: Get previous node value within text tokenized template

I'm new in XSLT so I hope I'll get some help here.

I'm trying to transform following XML

<?xml version="1.0"?><?xml-stylesheet type="text/xsl"?>
    <OrderLineItems>
    <OrderLineItem>
        <SKU>60</SKU>
        <Meta>Topic: one, Topic: two, Topic: three, Topic: four</Meta>
    </OrderLineItem>
    <OrderLineItem>
        <SKU>70</SKU>
        <Meta>Topic: one, Topic: two, Topic: three, Topic: four</Meta>
    </OrderLineItem>
    </OrderLineItems>

to

<ArticleNo>60.1</ArticleNo>
<ArticleNo>60.2</ArticleNo>
<ArticleNo>60.3</ArticleNo>
<ArticleNo>60.4</ArticleNo>

<ArticleNo>70.1</ArticleNo>
<ArticleNo>70.2</ArticleNo>
<ArticleNo>70.3</ArticleNo>
<ArticleNo>70.4</ArticleNo>

with following xslt which doesn't work

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="Meta" name="tokenize">
        <xsl:param name="separator" select="', '" />
        <xsl:for-each select="tokenize(.,$separator)">
                            <ArticleNo><xsl:value-of select="../SKU"/>.<xsl:value-of select="position()" /></ArticleNo>
        </xsl:for-each>
    </xsl:template>
  <xsl:template match="SKU" />

</xsl:stylesheet>

How can I access SKU correctly?

Using XSLT 2.0 the output can be achieved by making a small tweak in the shared XSL. The <SKU> value can be added to a variable and used to format the desired output.

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="Meta" name="tokenize">
        <xsl:param name="separator" select="', '" />
        <xsl:variable name="skuValue" select="../SKU" />
        <xsl:for-each select="tokenize(.,$separator)">
            <ArticleNo>
                <xsl:value-of select="$skuValue" />
                .
                <xsl:value-of select="position()" />
            </ArticleNo>
        </xsl:for-each>
    </xsl:template>
    <xsl:template match="SKU" />
</xsl:stylesheet>

Output

<ArticleNo>60.1</ArticleNo>
<ArticleNo>60.2</ArticleNo>
<ArticleNo>60.3</ArticleNo>
<ArticleNo>60.4</ArticleNo>
<ArticleNo>70.1</ArticleNo>
<ArticleNo>70.2</ArticleNo>
<ArticleNo>70.3</ArticleNo>
<ArticleNo>70.4</ArticleNo>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM