How to match the processing-instruction element in XSLT?
Asked Answered
I

2

10

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

Ionium answered 2/9, 2009 at 10:19 Comment(0)
B
17

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>
Bactria answered 2/9, 2009 at 10:30 Comment(3)
Sorry, its not working, i am just getting the content without any element.Ionium
hi, i am not getting the content when i use your second code... i m getting only <legalnotice/> this element...Ionium
So it works, then! My code was only a snippet to demonstrate how you'd go about this.Bactria
E
2

This is inherently a bad design, you seem to be trying to match start/end tags but without using the methods available to if you were to use an actual xml element.

Whilst you can match the start/end processing instructions its difficult with xpath to locate the nodes between said processing instructions. If you have nesting or repeated such instructions it can become even more difficult. And at the end of the day, all this is doing is trying to replicate what xml already does without using xml?

Enthalpy answered 2/9, 2009 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.