Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT - identify node followed by another node

Tags:

xml

xslt

xslt-2.0

I have a xml like this,

<doc>
    <p>para<x>para</x>para<x>para</x>para</p>
    <p>para<x>para</x><x>para</x>para</p>
</doc>

I need to add a ',' between <x> nodes if couple of <x> placed successively (<x> followed by another <x>node).

so, for above example xml, output should be,

<doc>
    <p>para<x>para</x>para<x>para</x>para</p>
    <p>para<x>para</x>,<x>para</x>para</p>
</doc>

I tried to write a xsl template fo identify successive <x> noted and added the ',' as follows,

 <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="x[following-sibling::*[1][self::x]]">
        <x>
            <xsl:apply-templates/>
        </x>
        <xsl:text>,</xsl:text>
    </xsl:template>

but it adds the ',' to the above both scenarios. (<x> followed by another <x>node and <x> followed by text)

Any idea to correct this xpath?

like image 728
sanjay Avatar asked Mar 02 '26 21:03

sanjay


1 Answers

By using following-sibling::*[1] the XPath only check for the nearest following sibling element, not considering text nodes. Try using following-sibling::node()[1] instead :

<xsl:template match="x[following-sibling::node()[1][self::x]]">
    <x>
        <xsl:apply-templates/>
    </x>
    <xsl:text>,</xsl:text>
</xsl:template>
like image 150
har07 Avatar answered Mar 04 '26 21:03

har07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!