How to match the processing-instruction element in XSLT?

Antony picture Antony · Sep 2, 2009 · Viewed 11.7k times · Source

I have some processing-instructions elements inside my xml content, for example :

<?legalnoticestart?>
<?sourcenotestart?>
<para>Content para</para>
<?sourcenoteend?>
<?literallayoutstart?>
<para>body content </para>
<?literallayoutend?>
<?legalnoticeend?>

How can i match these elements and get the content in the below required element format?

Required xml:

<legalnotice>
<sourcenote>
<p>Content para</p>
</sourcenote>
<literallayout>
<p>body content</p>
</literallayout>
</legalnotice>

Please advice....

Best Regards, Antony

Answer

butterchicken picture butterchicken · Sep 2, 2009

By default, an XSLT processor will ignore PIs - to match them in order to do fun and useful things, you can use the processing-instruction match in your template:

<xsl:template match="processing-instruction('legalnoticestart')">
  <legalnotice><xsl:value-of select="."/></legalnotice>
</xsl:template>

For example, the following Stylesheet:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="doc">
        <xsl:apply-templates select="processing-instruction('legalnoticestart')" />
    </xsl:template>

    <xsl:template match="processing-instruction('legalnoticestart')">
        <legalnotice><xsl:value-of select="."/></legalnotice>
    </xsl:template>
</xsl:stylesheet>

With this document:

<doc>
   <?legalnoticestart?>
   <?legalnoticeend?>
</doc>

Yields:

<?xml version="1.0"?>
<legalnotice>
</legalnotice>