Avbasot
Avbasot

Reputation: 363

Grabbing text between Processing Instructions in XSLT

I'm trying to run an XSLT on the below XML to wrap text between certain PI's with a new element:

Input XML:

<doc>
   <p>
      <?addition?>hello<?addition?> text1
   </p>
   <p>text2</p>
   <p>
      <?addition?>bye<?addition?> text2
   </p>
</doc>

I am trying to wrap the text between the addition-start and addition-end in a <u> element like below.

Desired output:

<doc>
   <p>
      <u>hello</u> text1
   </p>
   <p>text2</p>
   <p>
      <u>bye</u> text2
   </p>
</doc>

My current XSLT is incorrectly grabbing text nodes that are not inbetween PI's, current stylesheet:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="#all"
    version="2.0">
    <xsl:template
        match="@* | node()">
        <xsl:copy
            copy-namespaces="no"
            exclude-result-prefixes="#all"
            inherit-namespaces="no">
            <xsl:apply-templates
                select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//p/text()[preceding::processing-instruction('addition')]
                                   [following::processing-instruction('addition')]">
        <u><xsl:value-of select="." /></u>
    </xsl:template>
</xsl:stylesheet>

Is there a way to tweak my XSLT to achieve this and wrap only the text surrounded by PI's with a <u>?

Upvotes: 0

Views: 201

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167446

I think you want

<xsl:template match="p/text()[preceding-sibling::node()[1][self::processing-instruction('addition')]]
                             [following-sibling::node()[1][self::processing-instruction('addition')]]">
    <u><xsl:value-of select="." /></u>
</xsl:template>

https://xsltfiddle.liberty-development.net/ehVZvvF

And, as Daniel Haley pointed out in his comment, you can furthermore add an empty template <xsl:template match="processing-instruction('addition')"/> to remove the processing instructions.

https://xsltfiddle.liberty-development.net/ehVZvvF/1

Upvotes: 3

Related Questions