Search code examples
xmlxslt-2.0

How to handle Processing instructions in XSLT


I want to do some tasks using XSLT 2.0. I have explained my using following example.

Input:

<code>
    <bigin>
        <?codestuct a?>
        <butic>
            <a>a</a>
            <a>b</a>
        </butic>
        <?codestuct c?>
        <butic>
            <a>a</a>
            <a>b</a>
        </butic>
    </bigin>
    <medium>
        <?codestuct a?>
        <super>
            <p>para1</p>
        </super>
        <?codestuct b?>
        <super>
            <p>para2</p>
        </super>
        <?codestuct c?>
        <super>
            <p>para3</p>
        </super>
    </medium>
</code>

What I wanted to was add string if <super> processing-instruction equals to the <butic> processing-instruction.

As an example,

1st <super> element processing-instruction equals to 1st <butic> processing-instruction. Then found string should be printed in output.

But 2nd <super> element processing-instruction not equals to any <butic> element.

Expected output:

<output>
    <extreme>Founded</extreme>
    <extreme>Not Founded</extreme>
    <extreme>Founded</extreme>
</output>

Tried code:

<xsl:template match="medium">
    <output>
        <xsl:choose>
            <xsl:when test="preceding-sibling::bigin/processing-instruction('codestuct') = super/processing-instruction('codestuct')">
                <extreme>
                    <xsl:value-of select="'Founded'"/>
                </extreme>
            </xsl:when>
            <xsl:otherwise>
                <extreme>
                    <xsl:value-of select="'Not Founded'"/>
                </extreme>
            </xsl:otherwise>
        </xsl:choose>
    </output>
</xsl:template>

Solution

  • It is not quite clear what you want to compare and whether the elements matter but

      <xsl:template match="code">
          <output>
              <xsl:apply-templates select="medium/processing-instruction()"/>
          </output>
      </xsl:template>
      
      <xsl:template match="medium/processing-instruction()">
          <extreme>Not found</extreme>
      </xsl:template>
      
      <xsl:template match="medium/processing-instruction()[some $pi in /code/bigin/processing-instruction() satisfies deep-equal(., $pi)]">
          <extreme>Found</extreme>
      </xsl:template>
    

    gives

    <output>
       <extreme>Found</extreme>
       <extreme>Not found</extreme>
       <extreme>Found</extreme>
    </output>
    

    at https://xsltfiddle.liberty-development.net/ei5R4uG