stracktracer
stracktracer

Reputation: 1900

Match tag if a specific tag exists in the following siblings

I have an xml where my tag <T> is only to be transformed, if there is at least one tag <C> following behind it as sibling.

<Doc>
    <T>T1</T>
    <A>A1</A>
    <T>T2</T>
    <C>C2</C>
    <T>T3</T>
    <X>X1</X>
</Doc>

should become: T1A1T2C2X1

I currently have:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml"/>
    <xsl:template match="/">
        <xsl:element name="Doc">
            <xsl:apply-templates select="*" />
        </xsl:element>
    </xsl:template>

    <xsl:template match="A">
        <xsl:value-of select="."/>
    </xsl:template>

    <xsl:template match="C">
        <xsl:value-of select="."/>
    </xsl:template>

    <xsl:template match="X">
        <xsl:value-of select="."/>
    </xsl:template>

    <xsl:template match="T[following-sibling::* ??? exists C">
        <xsl:value-of select="."/>
    </xsl:template>

    <xsl:template match="*">
    </xsl:template>
</xsl:stylesheet>

Not sure how to realize the match="T[following-sibling::* ??? exists C"

Upvotes: 1

Views: 2222

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

Use:

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

    <xsl:template match="/*">
        <xsl:apply-templates select="*"/>
    </xsl:template>

    <xsl:template match="T[preceding-sibling::*[1][self::C]]"/>

    <xsl:template match="*">
        <xsl:value-of select="."/>
    </xsl:template>
</xsl:stylesheet>

Output:

T1A1T2C2X1

Upvotes: 1

Related Questions