Sumathi
Sumathi

Reputation: 83

To Remove only specified parent element not child element in xslt

Input xml like below.

<part type="frontmatter">
<section level="1"><title>THIEME Atlas of Anatomy</title>
........
</section>
<section level="1">
<title></title><para><emph type="bold">To access additional material
......
</section>
</part>
<part type="content">
<section level="1">
<title id="p001">Structure and Development of Organ Systems</title>
...
<section level="2">
<title>Suggested Readings</title>
.......
</section>
</section>
</part>

Output should be

<part type="frontmatter">
<section level="1"><title>THIEME Atlas of Anatomy</title>
........
</section>
<section level="1">
<title></title><para><emph type="bold">To access additional material
......
</section>
</part>
<part type="content">
<title id="p001">Structure and Development of Organ Systems</title>
...
<section level="2">
<title>Suggested Readings</title>
........
</section>
</part>

My xslt is:

<xsl:template match="section[position()=1]"><!-\-//-\->
    <xsl:if test="preceding-sibling::part[@type='content'][not(title)]">
        <part type="content">
        <xsl:apply-templates select="node() | @*"/>
        </part>
    </xsl:if>
</xsl:template>

I want to remove <section level="1"> element which is appearing under <part type="content"> where "title" element should not appear between these two elements. If "title" is appear under part element then should not make any change.

Upvotes: 0

Views: 531

Answers (1)

Tim C
Tim C

Reputation: 70608

If you want to remove section element, under a part element, where there is no preceding title, then the template match should look like this

<xsl:template match="part[@type='content']/section[@level='1'][not(preceding-sibling::title)]">

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" />

    <xsl:template match="part[@type='content']/section[@level='1'][not(preceding-sibling::title)]">
        <xsl:apply-templates />
    </xsl:template>

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

Note, in this particular example, you may be able to simplify it to this

<xsl:template match="part[@type='content']/section[1]">

So, just remove the section element if it is the first child element of part. This would not work if you could have elements other that title preceding the section.

Upvotes: 1

Related Questions