how to remove an element if its immediately following an element using xslt

Viewed 49

if any placeholder element with attribute x=”test” + text element immediately follow an hg* record that is a duplicate needs to be removed below is the sample xml:

        <block ID="IF5">
        <codes ID="IF5" x="hg5">
            <info>
                <name>ARTICLE</name> 
                <designator>1</designator>
            <info>
        </codes>
        <codes ID="IF5" x="hg5c">
            <info>
                <headtext>PUBLIC</headtext>
            </info>
        </codes>
        <placeholder ID="IF526" x="test">
            <text>SANA</text>
        </placeholder>
        <grade>
            <text>SANA</text>
        </grade>
        <placeholder ID="IF526" x="test">
            <text>SANA</text>
        </placeholder>
    </block>

expected output:

        <block ID="IF5">
        <codes ID="IF5" x="hg5">
            <info>
                <name>ARTICLE</name> 
                <designator>1</designator>
            <info>
        </codes>
        <codes ID="IF5" x="hg5c">
            <info>
                <headtext>PUBLIC</headtext>
            </info>
        </codes>
        <grade>
            <text>SANA</text>
        </grade>
        <placeholder ID="IF526" x="test">
            <text>SANA</text>
        </placeholder>
    </block>

my xslt code look like below:

        <xsl:template match="placeholder[@x='test']" >
        <xsl:choose>
            <xsl:when test="preceding-sibling::*[1][codes[@x='hg*']]">
                <!-- do nothing-->
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
1 Answers

try this as just a template that will match :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  xmlns="http://www.w3.org/1999/xhtml"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

   <xsl:template match="placeholder[@x='test'][preceding-sibling::*[1][self::codes[substring(@x,1,2)='hg']]]"/> 

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

</xsl:stylesheet>
Related